按下后退按钮时如何使片段替换为特定片段 [英] How to make fragment replaced by a specific fragment when back button pressed

查看:99
本文介绍了按下后退按钮时如何使片段替换为特定片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含导航抽屉的应用程序,其中一个片段是home片段,例如,如果用户在fr1上按下,然后在fr2上按下,则我希望该应用程序在其他片段中按向后按钮时转到该片段fr3我希望它返回到主页按钮(其中fr1,2,3是导航抽屉的片段,请注意,应用程序中还有其他片段,我不希望它们在按下后退按钮时回到主页)

I have an app that contain a navigation drawer one of the fragments is the home fragment I want the app when the back button pressed in some other fragments to go to the home fragment for example if the user pressed on fr1 then fr2 then fr3 I want it to return back to the home button (where fr1,2,3 are the fragments of the navigation drawer and notice that there is other fragments in the app I don't want them to go to the home when back button pressed)

推荐答案

如果您的后堆栈中有多个片段,您将不会仅仅通过popBackStack()到达您的家庭片段,因为它只会逆转最后一个操作.例如,它有3个片段(home,fr1,fr2),首先您将到达fr2,然后才是home.如果您想直接通过BackPress()返回首页片段,则应将当前的内容替换为首页片段.

If you have multiple fragments in your backstack you won't get to your home fragment just by popBackStack() as it just reverses one last operation. For example, it you have 3 fragments (home, fr1, fr2) first you'll get to fr2 and just then to home. If you want to get to home fragment directly onBackPress() you should replace what you currently have with your home fragment.

    @Override
    public void onBackPressed() {
        int stackCount = getFragmentManager().getBackStackEntryCount();
        if (stackCount == 1) {
            super.onBackPressed(); // if you don't have any fragments in your backstack yet.
        } else {
        // just replace container with fragment as you normally do;

        FragmentManager fm = getFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);//clear backstackfirst and then you can exit the app onbackpressed from home fr
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.container, new HomeFragment());
        transaction.commit();
        }
    }

如何检查当前可见的片段

How to check the current visible fragment

Fragment f = getFragmentManager().findFragmentById(R.id.container);
if (f instanceof HomeFragment) {
//do smth
} 

这篇关于按下后退按钮时如何使片段替换为特定片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆