Using Toolbar with Fragments

后端 未结 5 2065
小蘑菇
小蘑菇 2020-12-07 13:46

I am trying to create a viewpager that swipes through 3 different fragments each with a different toolbar. I have implemented the new toolbar in an activity before and got i

5条回答
  •  独厮守ぢ
    2020-12-07 14:22

    I have seen a lot of answers mentioning to setSupportActionBar for toolbar inside Fragment but this approach may go wrong if you are having a a toolbar in Activity and a separate Toolbar in Fragment.

    1. As you shift setSupportActionBar from Activity's Toolbar to Fragment's toolbar, You may face duplication of MenuItem even you try to override using setHasOptionsMenu(true).
    2. Secondly If you want to update Activity's Toolbar you see your changes are not reflected because of setSupportActionBar inside your Fragment.

    So in order to avoid this I recommend to use toolbar methods like this inside fragment to inflate menu and use

     toolbar = (Toolbar) view.findViewById(R.id.toolbar_frag);
        toolbar.inflateMenu(R.menu.frag_menu_items);
        Menu menu = toolbar.getMenu();
    

    and use Toolbar.OnMenuItemClickListener interface to receive with menuItems click events.

    Edit (Section Copied from MrEngineer13 answer)

    and if you are worried about the back button you can set it like this

    toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           //What to do on back clicked
       }
    });
    

提交回复
热议问题