我有一个可以包含多个 fragment 的 Activity 。每个 fragment 都可以在 ActionBar 中有自己的菜单项。到目前为止这工作正常,每个项目都是可点击的并执行所需的操作。
我的问题如下。在 MainActivity 中,我声明了以下行以拦截对 ActionBar 的 HomeIcon 的调用:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
clearBackStack();
setHomeFragment();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
我在 Activity 中声明了它,因为我希望每个 Fragment 都应该调用它,这样我就不必在每个 fragment 中捕获 android.R.id.home 的情况。
在一个 fragment 中,我使用了 setDisplayHomeAsUpEnabled(true),这样我就得到了 ActionBar 图标左侧的小箭头。当在此 fragment 中单击 HomeIcon 时,我不想设置 HomeFragment,我想设置最后显示的 fragment 。所以我有一个 onOptionsItemSelected - fragment 中的方法:
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
setLastFragment();
return true;
...
然而,这并不像我希望的那样工作。首先调用 Activity 的 onOptionsItemSelected,捕获 MenuItem 并重定向到 HomeFragment。使用在其他 fragment 中声明的其他 MenuItems,我可以检查是否看到相同的行为。首先调用 Activity,不捕获 MenuItem(默认情况),然后重定向到 super.onOptionsItemSelected(item)。
看来 Android 处理菜单点击的方式就是这种情况。第一个 Activity ,然后 fragment 。有没有办法改变这个?我不想将 android.R.id.home-case 放在每个 fragment 中并在那里处理。有没有更好的方法来做到这一点?
最佳答案
我刚遇到这个问题,我用下面的代码解决了这个问题。
在 Activity 的 onOptionsItemSelected
函数中,添加:
if (id == android.R.id.home){
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if(null != currentFragment && currentFragment.onOptionsItemSelected(item)){
return true;
}
}
在 fragment 的onOptionsItemSelected
方法中,您处理相应的事情。
这样,如果 fragment 对菜单项有任何事情要做,它就会去做并返回 true 以停止任何其他进程。
而如果fragment与这个item没有任何关系,它会返回false或者调用super.onOptionsItemSelected方法最终可能会返回false让其他人处理。
关于android - Activity 中的 OnOptionsItemSelected 在 fragment 中的 onOptionsItemSelected 之前被调用。其他方式可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679917/