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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With