【发布时间】:2019-09-10 23:49:46
【问题描述】:
我想根据我的NavController 的当前目的地更改我的ActionBar 中显示的菜单项。通过“更改”,我的意思是为每个目的地膨胀指定的 menu-xml。
该行为可以与新导航系统更改 ActionBar 标题的集成方式进行比较,具体取决于导航 xml 中目标片段的给定 android:label。
到目前为止,我使用新的 Android 导航设置了 ActionBar 和 DrawerLayout 的基本活动。我还创建了所有必要的 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