(Deprecated) Fragment onOptionsItemSelected not being called

Same problems happened to me:

onMenuItemSelected events didn’t get called in Fragment

Searched google cann’t find a solution, and add onMenuItemSelected method in FragmentActivity doesn’t solve it.

Finally resolve it by following reference to http://developer.android.com/guide/topics/ui/actionbar.html

Note: If you added the menu item from a fragment, via the Fragment class’s onCreateOptionsMenu callback, then the system calls the respective onOptionsItemSelected() method for that fragment when the user selects one of the fragment’s items. However the activity gets a chance to handle the event first, so the system calls onOptionsItemSelected() on the activity before calling the same callback for the fragment.

Which means only if you don’t have that menu item handler in onOptionsItemSelected() on the activity, the onOptionsItemSelected() on the fragment will be called.

Code as following
—–Remove the handler for R.action.add on FragmentActivity):

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case android.R.id.home:
            popBackStack();             
            return true;        
        case R.id.action_search:
            searchAction();
            return true;
        case R.id.action_logout:
            userLogout();
            return true;
        //case R.id.action_add:
            //return true;    
        default:
            return super.onOptionsItemSelected(item);
    }   
}

And the handler for R.action.add on Fragment looks like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Log.d("onOptionsItemSelected","yes");
    switch (item.getItemId()) {
        case R.id.action_add:
            add();
            return true;    
        default:
            return super.onOptionsItemSelected(item);
    }
}

Finally, remember to add

    setHasOptionsMenu(true);

in your onCreate method in Fragment

Leave a Comment