Nima Nima - 5 months ago 14
Android Question

Fragment's onOptionsItemSelected doesn't get called

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?

Answer

You are not chaining to the superclass in the activity methods. Please have onCreateOptionsMenu() return super.onCreateOptionsMenu(menu), and have onOptionsItemSelected() return super.onOptionsItemSelected(item) (except for the item that you are handling, which should return true to indicate that you have handled the event).