androidfragmentactionbardrawertoggleup-navigation

onOptionsItemSelected not called pressing up navigation icon on fragment


Title is almost self explanatory.

Architecture:

I disable the Drawer Toggle and set the Home As Up indicator just before replace the fragments:

        mDrawerToggle.setDrawerIndicatorEnabled(false);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);
        actionBar.setDisplayHomeAsUpEnabled(true);

Then, when the UP icon is clicked, nothing happen. I debugged it and the onOptionsItemSelected method is not called.

FYI, all the other buttons that I added to the menu (search, refresh, etc) work and onOptionsItemSelected is called.


Solution

  • If you're implementing onOptionsItemSelected in the drawer activity, it will no longer be called in the fragment too, unless you return false in the activity.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.home:
            return false; //The fragment will take care of it
        default:
            break;
        }
    return false;
    }
    

    Hope it helps!

    Update

    You can also try starting a new activity and loading that fragment in the activity, as I said. Since you're already passing data through a Bundle to your child fragment, you can do the same for the activity.

    Intent intent = new Intent(getActivity(), NewActivity.class);
    Bundle bundle = new Bundle();
    bundle.putWhatever(key, value); //There's no such method, just a generalization
    intent.putExtras(bundle);
    startActivity(intent);