本文介绍了如何在片段中实现onBackPressed()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以像在Android Activity中实现方法一样在Android Fragment中实现onBackPressed()?

Is there a way in which we can implement onBackPressed() in Android Fragment similar to the way in which we implement in Android Activity?

因为Fragment生命周期没有onBackPressed().还有其他替代方法可以在Android 3.0片段中超越onBackPressed()吗?

As the Fragment lifecycle do not have onBackPressed(). Is there any other alternative method to over ride onBackPressed() in Android 3.0 fragments?

推荐答案

我以这种方式解决了覆盖Activity中的onBackPressed的问题.提交前,所有FragmentTransaction均为addToBackStack:

I solved in this way override onBackPressed in the Activity. All the FragmentTransaction are addToBackStack before commit:

@Override
public void onBackPressed() {

    int count = getSupportFragmentManager().getBackStackEntryCount();

    if (count == 0) {
        super.onBackPressed();
        //additional code
    } else {
        getSupportFragmentManager().popBackStack();
    }

}

这篇关于如何在片段中实现onBackPressed()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 19:50