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

androidandroid-fragmentactivityandroid-fragmentsandroid-menu

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?

Best Answer

I just encounter this problem, and I have made it work using following code. In the activity's onOptionsItemSelectedfunction, add:

if (id == android.R.id.home){
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
        if(null != currentFragment && currentFragment.onOptionsItemSelected(item)){
            return true;
        }
    }

And in the fragment's onOptionsItemSelected method, you handle the corresponding things. In this way, if the fragment has any things to do for the menu item, it will do it and return true to stop any other process. And if the fragment does not have anything to do with this item, it will return false or call super.onOptionsItemSelected method which may eventually return false to let others process it.

Related Topic