Android: How to recreate Action bar when fragment changed

后端 未结 4 1799
借酒劲吻你
借酒劲吻你 2021-01-31 09:54

I have an activity showing a few fragments. Activity view contains only ViewPager initialized with custom FragmentPagerAdapter. This adapter provide navigation among 3 fragments

相关标签:
4条回答
  • 2021-01-31 10:29

    If you are using ActionBar tabs, You would like to see this answer:

    How can I change Action Bar actions dynamically?

    0 讨论(0)
  • 2021-01-31 10:31

    Finally I couldn't find any sound way to achieve this.

    The best would be to make actionbar a part of fragment, not activity, but it's impossible.

    I end up with clearing actionbar menu and title when swipe begins(you can set special listener in PageView) and setting menu and title again when swipe complete and new fragment are shown.

    In gives some time lag and actionbar looks strangely empty during swipe, but it's best you can do.
    Android API is c...

    0 讨论(0)
  • 2021-01-31 10:37

    It can be done by implementing onCreateOptionsMenu and calling setHasOptionsMenu(true) in the onAttach callback in each fragment and change the actions accordingly.

    To show the fragment without any actions setHasOptionsMenu(false) in it

    0 讨论(0)
  • 2021-01-31 10:41

    You can ask android to re-create the actionbar before it automatically does by calling invalidateOptionsMenu();

    Do this somewhere close to the point where you change fragments to try and decrease the 'lag' between the fragment and actionbar changing.

    Edit

    a complete solution may look like this:

    class activity extends Activity{
    
    private void switchFragment(){
    
    ...do fragment changing stuff
    
    activity.invalidateOptionsMenu();
    
    }
    
    }
    
    class someFragment extends Fragment{
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
    {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
    
    
        //fragment specific menu creation
    }
    
    }
    

    whichever fragment is open during the

    activity.invalidateOptionsMenu();
    

    will then call its

     onCreateOptionsMenu
    

    and you can do fragment specific menu creation in there

    0 讨论(0)
提交回复
热议问题