Replace toolbar layout according to the displayed fragment

后端 未结 1 1861
既然无缘
既然无缘 2021-01-31 05:08

I have an activity with navigation drawer which replace the main_fragment_container on the activity. When one of the fragments is displayed I want to change the layout of the to

1条回答
  •  心在旅途
    2021-01-31 05:27

    Not sure what you are trying to accomplish but I think, if possible, you should approach this by letting the fragments customize your toolbar rather than replacing it. Your can let your fragments hide/show views on the toolbar depending on your needs.

    Add setHasOptionsMenu(true); in the fragments OnCreateView() and then override onOptionsMenuCreated()

    Like this:

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.result_list, container, false);
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.this_frag_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    

    If you need to do more specific things with the toolbar you can get the instance using

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

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