My fragment replaces the parent Activity options with a specific option item but when I click on the item, only activity's onOptionItemSelected
gets called eventhough I've overridden the method inside Fragment. Am I missing something?
Fragment's methods:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d(TAG, "Fragment.onCreateOptionsMenu");
if (mPasteMode) {
menu.clear();
inflater.inflate(R.menu.contexual_paste, menu);
getActivity().getActionBar().setTitle("PasteMode");
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "Fragment.onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.context_action_paste:
Toast.makeText(getActivity(),
"It worked ",
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Activity's methods:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "MainActivitiy.onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(this, "Action Refresh selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
Logcat output:
MainActivity.onCreateOptionsMenu
Fragment.onCreateOptionsMenu
MainActivitiy.onOptionsItemSelected
So how can I have the onOptionsItemSelected
of the fragment called?
If your Activity's onOptionsItemSelected method returs true, the call is consumed in activity and Fragment's onOptionsItemSelected is not called. So, return false in your Activity onOptionsItemSelected method or parent class implementation via super.onOptionsItemSelected call (default implementation returns false).
According Activity class javadoc, method Activity.onOptionsItemSelected should:
Return false to allow normal menu processing to proceed, true to consume it here