Search code examples
androidandroid-fragmentsandroid-fragmentactivityandroid-menu

OnOptionsItemSelected in activity is called before onOptionsItemSelected in fragment. Other way possible?


I have an activity which can contain several fragments. Each of the fragments can have their own menu entries in the ActionBar. This works fine so far and each item is clickable and performs the desired action.

My problem is the following. In the MainActivity I declared the following lines to intercept calls to the HomeIcon of the ActionBar:

public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            clearBackStack();
                    setHomeFragment();
            return true;
        default:
            return super.onOptionsItemSelected(item);

        }
    }

I declared it in the Activity because I wanted that every Fragment should call this so that I don't have to catch the android.R.id.home case in each fragment.

In one Fragment I am using setDisplayHomeAsUpEnabled(true), so that I get the little arrow left of the ActionBar Icon. When the HomeIcon is clicked in this fragment I don't want to set the HomeFragment, I want to set the Fragment which was last displayed. So I have a onOptionsItemSelected - Method in the Fragment:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {

    switch (menuItem.getItemId()) {
    case android.R.id.home:
        setLastFragment();
               return true;
    ...

However this does not work the way I wanted it to work. The Activity's onOptionsItemSelected is called first, catches the MenuItem and redirects to the HomeFragment. With the other MenuItems declared in other fragments i can check the see the same behaviour. Activity is called first, doesn't catch the MenuItem (default case) and then redirects to super.onOptionsItemSelected(item).

So it seems that this is the case how Android handles the Menu Clicks. First Activity, then Fragment. Is there a way to change this? I don't want to put the android.R.id.home-case in every fragment and handle it there. Is there a nicer way to do this?


Solution

  • According to the developers reference,

    "Return false to allow normal menu processing to proceed, true to consume it here."

    So I would try returning 'false' by default in the Activity's implementation of onOptionsItemSelected(), this way the event will pass on to the Fragment's implementation if it is not caught.