问题
I have a main activity in which I designate tabs using three fragments. I have a button on the ActionBar which navigates to a different fragment say "Info about the app" Once user navigates to this particular fragment (Info) I disable it so that it is not called again and again. Then on the back key in the main activity I re-enable it. So far so good. But I am not able to re-enable it for one scenario: Say if user navigates to the info fragment and does not press back, but however if he navigates to a different tab, the info button is still disabled because back-press has not been called. I tried a lot of things in onStart() and onResume() of fragments but I am not able to reference the menuItem in any of those as I get a null pointer.
Code Reference: (MainActivity while calling the info fragment from onOptionsSelected):
public boolean onOptionsItemSelected(MenuItem item) {
mMenuItem = item;
switch (item.getItemId()) {
case R.id.info:
Tab d = getActionBar().getSelectedTab();
System.out.println(""+d.getText().toString());
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
String a = d.getText().toString();
if(a.equalsIgnoreCase("Reminders")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent, fragmentcontact);
mMenuItem.setEnabled(false);
//mMenuItem.setIcon(R.drawable.btn_age_01);
}
else if(a.equalsIgnoreCase("Notifications")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent2, fragmentcontact);
mMenuItem.setEnabled(false);
}
else if(a.equalsIgnoreCase("Contacts")){
FragmentContact fragmentcontact = new FragmentContact();
fragmentTransaction.replace(R.id.realtabcontent3, fragmentcontact);
mMenuItem.setEnabled(false);
}
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
break;
on Back key(Main Activity):
@Override
public void onBackPressed() {
mMenuItem.setEnabled(true);
super.onBackPressed();
}
回答1:
The solution was very simple, to set an options menu for individual "Fragments" use:
setHasOptionsMenu(true);
Cheers!!
来源:https://stackoverflow.com/questions/20393016/enable-an-actionbar-button-each-time-navigation-within-tabs-occurs