根据导航目标更新ActionBar菜单

问题描述 投票:0回答:1

我想根据ActionBar的当前目的地更改我的NavController中显示的菜单项。通过“更改”,我的意思是为每个目的地充气指定的menu-xml。

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

到目前为止,我使用新的Android导航设置了ActionBarDrawerLayout的基本活动。我还创建了所有必要的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);
}

我想在每个目标片段中使用单独的工具栏,但我放弃了这个想法,因为我会丢失汉堡包图标和后箭头图标之间的过渡动​​画。

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

java android android-fragments android-actionbar android-architecture-navigation
1个回答
0
投票

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

在目的地Fragment中,我现在正在使用它:

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

    menu.clear();
    inflater.inflate(R.menu.toolbar_items_idle, menu);
}
© www.soinside.com 2019 - 2024. All rights reserved.