oncreate option menu of fragment stoppng activity oncreateoptionmenu

oncreate option menu of fragment stoppng activity oncreateoptionmenu

我有一个 activity 和五个 fragments.I 在选项菜单中有一个导航抽屉按钮,可以帮助我在一个片段上导航 fragment.But 我想将其更改为返回 button.Currently 后退按钮可以正常工作 correctly.But 并且 activity 选项菜单也可以正常工作,它会带来导航抽屉 up.How 来阻止它?

这是我的抽屉

主要活动

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.container, new SettingsFragment());
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();
            break;       
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            break;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

片段

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            getFragmentManager().popBackStack();
            return true;
        default:
            break;
    }
    return super.onOptionsItemSelected(item);
}

实际上,当我 select 两个选项菜单中的选项菜单主代码都有效时,我只希望片段选项菜单有效。我怎样才能阻止它?请帮忙

首先,在您的 activity 中创建一个标志来检查主页按钮是否作为后退按钮:isBackShow = false。然后,在 onOptionsItemSelected:

 case android.R.id.home: // show drawer or pop backstack base on flag
        if(isBackShow)
        getFragmentManager().popBackStack();
        mDrawerLayout.openDrawer(GravityCompat.START);
        return true;

在你的 SettingsFragment 中,你可以在 onCreateView 中或你想要的地方更改父亲 Activity 的标志:

if(getActivity() instanceof YourFatherActivity){
        ((YourFatherActivity)getActivity()).isBackShow = true;
        // You can also change drawer icon to back icon here.
}

不过我没有检查代码,据我所知,此代码可以使用。希望对您有所帮助。