简体   繁体   中英

onOptionsItemSelected not called pressing up navigation icon on fragment

Title is almost self explanatory.

Architecture:

  • I have Main activity that extends AppCompatActivity.
  • Also I have a drawer layout. Each option of this menu opens a fragment.
  • Each fragment has its own menu layout by setHasOptionsMenu(true) with its own buttons. The home button of their menus is still an access to open the drawer layout.
  • One of the fragments has a list of items and when one of these items is clicked a new child fragment is opened. ( HERE IS THE PROBLEM ) I want this child fragment to be able to navigate up to its parent by clicking on the up icon on its toolbar.

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM