Android Toolbar Adding Menu Items for different fragments

后端 未结 10 1653
野性不改
野性不改 2020-11-28 22:51

I have a toolbar as well as a navigation drawer. When I start my app, the toolbar and navigation drawer are created. When I click items in the navigation drawer, it starts n

10条回答
  •  孤城傲影
    2020-11-28 23:29

    The best way to do it :

    1. Find toolbar in Activity and set it as supportActionBar.

    Toolbar actionBarToolBar = (Toolbar) findViewById(R.id.my_toobar);
    setSupportActionBar(actionBarToolBar);
    

    2. Then It will be a piece of cake to handle option menus for different fragments over a same Activity. Do following things in each fragment as you want:

    In OnCreateView Method call

    setHasOptionsMenu(true);
    

    And Lastly,

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
    

    And to manage menu items click, we have onOptionsItemSelected:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search :
                Log.i("item id ", item.getItemId() + "");
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    

提交回复
热议问题