我最近开始更新我的应用程序,使用Android 5.0中引入的新工具栏组件,以支持在操作栏上使用自定义视图。我跟随导游来到这里:http://antonioleiva.com/material-design-everywhere/添加工具栏效果良好。问题是,我使用的导航结构中有一个MainActivity,并通过在后台添加Fragments来替换内容。我正在覆盖Fragments中的onCreateOptionsMenu和onOptionsItemSelected方法,以设置工具栏中的菜单项,当我切换Fragments时,图标会适当更改,并且在第一个Fragment上调用onOptionsIItemSelected,但当我将Fragment添加到backback时不会调用。MainActivity中的onOptionsItemSelected函数甚至没有被调用,因此该事件没有被Activity使用。我也尝试过只替换Fragment而不将其添加到backback中,但onOptionsItemSelected仍然没有被调用。更改内容Fragment后,要调用onOptionsItemSelected,我缺少什么?相关代码张贴在下面。
应用程序主题:
<style name="AppThemeLight" parent="@style/Theme.AppCompat.Light">
<item name="actionMenuTextColor">@color/white</item>
<item name="android:windowDisablePreview">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowActionBar">false</item>
</style>
在MainActivity:中添加工具栏
Toolbar toolbar = (Toolbar)findViewById( R.id.toolbar );
if (toolbar != null) {
setSupportActionBar( toolbar );
getSupportActionBar().setDisplayHomeAsUpEnabled( true );
toolbar.setNavigationIcon( R.drawable.toolbar_icon_menu );
}
MainActivity:中的菜单功能
@Override
public boolean onCreateOptionsMenu( Menu menu ) {
Log.v( "Main", "onCreateOptionsMenu" );
return super.onCreateOptionsMenu( menu );
}
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
Log.v( "Main", "onOptionsItemSelected" );
return super.onOptionsItemSelected( item );
}
顶级片段菜单功能:
@Override
public void onCreateOptionsMenu( Menu menu, MenuInflater inflater ) {
super.onCreateOptionsMenu( menu, inflater );
inflater.inflate( R.menu.main_looks, menu );
}
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
switch (item.getItemId()) {
case R.id.miOptions:
onOptions();
return true;
default:
return super.onOptionsItemSelected( item );
}
}
Fragment on backback 中的菜单功能
@Override
public void onCreateOptionsMenu( Menu menu, MenuInflater inflater ) {
super.onCreateOptionsMenu( menu, inflater );
inflater.inflate( R.menu.user, menu );
}
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
Log.v( "User", "onOptionsItemSelected" );
switch (item.getItemId()) {
case R.id.miUserShare:
onShareUser();
return true;
case R.id.miUserEdit:
onEditUserProfile();
return true;
default:
return super.onOptionsItemSelected( item );
}
}
在对其他Fragments进行更改时偶然解决了问题,并注意到onOptionsItemSelected是从布局更简单的Fragments中调用的。事实证明,出于某种原因将ScrollView作为片段布局的顶级组件会干扰工具栏接收触摸事件。通过将ScrollView包装在一个额外的RelativeLayout中(任何容器布局都可能起作用),可以调用OptionsItemSelected。我猜这与Toolbar组件现在是视图层次结构的一部分有关——我想不出为什么为ScrollView添加包装会解决这个问题。如果有人能帮助解释这种奇怪的行为,我们将不胜感激。
不要忘记在片段的OnCreate中调用setHasOptionsMenu(true)