Handling ActionBar title with the fragment back stack?

前端 未结 11 1469
挽巷
挽巷 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:36

    As described here my solution is adding this code to MainActivity onCreate method(): and changing actionbar title

    FragmentManager fragmentManager=getSupportFragmentManager();
    fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            Fragment currentFragment = fragmentManager.findFragmentById(R.id.My_Container_1_ID);
            currentFragment.onResume();
        }
    });
    

    and changing actionbar title in fragment's onResume() method

    @Override
    public void onResume() {
        super.onResume();
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        ActionBar actionBar = activity.getSupportActionBar();
        if(actionBar!=null) {
            actionBar.setTitle("Fragment Title");
            actionBar.setSubtitle("Subtitle");
        }
    
    }
    

提交回复
热议问题