Handling ActionBar title with the fragment back stack?

前端 未结 11 1471
挽巷
挽巷 2020-12-07 13:10

I have an Activity where I load in a ListFragment and, upon clicking, it drills down a level and a new type of ListFragment is shown,

11条回答
  •  春和景丽
    2020-12-07 13:40

    It is best to let the OS do as much of the work as possible. Assuming each fragment is properly named using .addToBackStack("title") then you can override onBackPressed something like this to achieve desired behavior:

    // this example uses the AppCompat support library
    // and works for dynamic fragment titles
    @Override
    public void onBackPressed() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        int count = fragmentManager.getBackStackEntryCount();
        if (count <= 1) {
            finish();
        }
        else {
            String title = fragmentManager.getBackStackEntryAt(count-2).getName();
            if (count == 2) {
                // here I am using a NavigationDrawer and open it when transitioning to the initial fragment
                // a second back-press will result in finish() being called above.
                mDrawerLayout.openDrawer(mNavigationDrawerFragment.getView());
            }
            super.onBackPressed();
            Log.v(TAG, "onBackPressed - title="+title);
            getSupportActionBar().setTitle(title);
        }
    }
    

提交回复
热议问题