Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Menu Item icon from fragment?

How can I access my Menu from my fragment and then change the icon of one of the menu items there?

What I am doing is querying my local DB to see if a certain entry exists when the fragment is shown. If it does display a solid icon, if not, display an outlined icon.

like image 450
Micro Avatar asked Oct 20 '15 20:10

Micro


1 Answers

In your fragments onCreate() method you can use setHasOptionsMenu(true) to allow your fragment to handle different menu items than it's root Activity. So you could do something like this in your fragment:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

And then, you can override any of the menu life-cycle methods in your fragment:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_fragment, menu);
    // You can look up you menu item here and store it in a global variable by 
    // 'mMenuItem = menu.findItem(R.id.my_menu_item);'
}

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    MenuItem menuItem = menu.findItem(R.id.menu_item_to_change_icon_for); // You can change the state of the menu item here if you call getActivity().supportInvalidateOptionsMenu(); somewhere in your code
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    // Handle actions based on the id field.
}
like image 156
Mike Avatar answered Oct 10 '22 18:10

Mike