Android - How to access actionbar's menu items in fragment class

前端 未结 5 1656
别那么骄傲
别那么骄傲 2020-12-08 19:29

How should I access the actionbar\'s menu items in fragment ? I have tried this but nothing happened

@Override
public boolean onOptionsItemSelected(MenuItem          


        
5条回答
  •  -上瘾入骨i
    2020-12-08 19:36

    You cant access directly ActionBar menu items in a Fragment. What you can do is put setHasOptionsMenu(true); in onCreateView function in fragment class and this calls the function onCreateOptionsMenu(Menu menu) in the corresponding activity.

    There, you can access all the menu items you have in the action bar. You can use:

    MenuItem item = menu.getItem(index);
    

    You have one example of using this:

    in fragment onCreateView class:

    setHasOptionsMenu(true);
    

    in corresponding activity class:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem item = menu.getItem(0);
        if(condition)
            item.setVisible(true);
        else 
            item.setVisible(false);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
           case R.id.action_logout:
               makeLogout();
               return  true;
           default :
               return super.onOptionsItemSelected(item);
        }
    
    }
    

提交回复
热议问题