![](/img/trans.png)
[英]Toolbar back button is not calling onOptionsItemSelected Android
[英]Android Toolbar Not Calling onOptionsItemSelected From Fragments On Backstack
我最近开始更新我的应用程序以使用Android 5.0中引入的新工具栏组件,转而使用操作栏上的自定义视图。 我按照这里的指南: http : //antonioleiva.com/material-design-everywhere/并添加工具栏工作正常。 问题是,我正在使用导航结构,我有一个MainActivity,并通过将碎片添加到backstack来替换内容。 我正在覆盖片段中的onCreateOptionsMenu和onOptionsItemSelected方法来设置工具栏中的菜单项,当我切换片段时图标会发生相应的变化,并且在第一个片段上调用onOptionsItemSelected,但是当我向其添加片段时不调用堆栈中。 甚至没有调用MainActivity中的onOptionsItemSelected函数,因此Activity不会使用该事件。 我还尝试过更换片段而不将其添加到backstack,但仍未调用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 );
}
}
在Backstack上的Fragment中的菜单功能
@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 );
}
}
在更改其他片段时注意到问题,并注意到使用更简单的布局从片段调用onOptionsItemSelected。 事实证明,由于某些原因,将ScrollView作为Fragment布局的顶级组件会干扰工具栏接收触摸事件。 通过将ScrollView包装在额外的RelativeLayout中(任何容器布局可能都有效),可以调用onOptionsItemSelected。 我猜这与工具栏组件现在是视图层次结构的一部分有关 - 无法想到为什么为ScrollView添加包装器可以解决问题。 如果有人能帮助解释这种奇怪的行为,我们将不胜感激。
别忘了在片段的OnCreate中调用setHasOptionsMenu(true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.