Search code examples
androidandroid-fragmentsfragmentmenuitemoptionmenu

How to control OptionMenuItem from fragment and MainActivity?


I have an option menu item on my action bar, in this option menu i have 4 items one of them is logout. well logout item i control it from MainActivity (it's work) the problem is how to control the other 3 items from the fragment because i need to use some objects and methods from fragment Class so there is any solution to control the 3 items from fragment and the logout item from the MainActivity ?


Solution

  • You can create and handle option menu items in fragments as follows:

    1. In onCreate or onCreateView call setHasOptionsMenu(true)

    2. Override onCreateOptionsMenu(Menu, MenuInflater) and inflate the fragment related menu there

    3. Override onOptionsItemSelected(MenuItem) and handle menu option clicks there