根据导航目的地更新 ActionBar 菜单

Update ActionBar menu depending on navigation destination

我想根据 NavController 的当前目的地更改 ActionBar 中显示的菜单项。 "change" 我的意思是为每个目的地膨胀指定的 menu-xml。

该行为可以与新导航系统更改 ActionBar 标题的集成方式进行比较,具体取决于 navigation-xml 中目标片段的给定 android:label

到目前为止,我使用新的 Android 导航设置了带有 ActionBarDrawerLayout 的基本 activity。我还创建了所有必要的 XML 文件和片段以在它们之间导航。

...

@Override
protected void onCreate(Bundle savedInstanceState)
{
    ...    

    this._drawerLayout = this.findViewById(R.id.drawer_layout);

    Toolbar toolbar = this.findViewById(R.id.action_bar);
    this.setSupportActionBar(toolbar);

    ActionBar actionbar = Objects.requireNonNull( this.getSupportActionBar() );
    actionbar.setDisplayHomeAsUpEnabled(true);
    actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);

    NavigationView navigationView = this.findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(menuItem -> {
        menuItem.setChecked(true);
        this._drawerLayout.closeDrawers();

        return true;
    });

    NavController navController = Navigation.findNavController(this, R.id.navigation_host);
    NavigationUI.setupWithNavController(toolbar, navController, this._drawerLayout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Here I inflate the ActionBar menu that is kept between all destinations.
    // Instead of keeping the same menu between all destinations I want to display different menus depending on the destination fragment.
    this.getMenuInflater().inflate(R.menu.actionbar_items, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    switch(item.getItemId())
    {
        case android.R.id.home:
            this._drawerLayout.openDrawer(GravityCompat.START);
            return true;
        case R.id.appbar_search:
            return true;
    }

    return super.onOptionsItemSelected(item);
}

我考虑过在每个目标片段中使用单独的工具栏 但我放弃了这个想法,因为我会失去汉堡图标和 back-arrow 图标之间的过渡动​​画。

有没有办法通过新的导航系统或任何其他方式实现这一目标?

我找到了一种方法来实现所需的行为,方法是在展开更新后的布局之前调用 menu.clear();。我仍然想知道新的导航系统是否有内置的方法来实现这一点。

在我现在使用的目标片段中:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    super.onCreateOptionsMenu(menu, inflater);

    menu.clear();
    inflater.inflate(R.menu.toolbar_items_idle, menu);
}

我刚刚测试了这个。使用导航库的当前版本 (2.2.2),当您四处导航时,将添加和删除由每个片段扩展的菜单项。

但是默认不调用onCreateOptionsMenu!为了使事情正常进行,您必须撒上魔法粉并在初始化期间调用 setHasOptionsMenu(true)

请注意,包含 activity 的任何菜单项都将始终与当前片段中的菜单项并排显示,因此如果您不想要任何公共菜单项,最简单的方法可能是不扩充菜单在 Activity.

旁注:在 Fragment class 中,onCreateOptionsMenu(menu, inflater) 是一个空方法,因此在您的代码中对 super.onCreateOptionsMenu(menu, inflater) 的调用是空操作。