gpt4 book ai didi

android - (已弃用) fragment onOptionsItemSelected 未被调用

转载 作者:IT老高 更新时间:2023-10-28 13:09:40 27 4
gpt4 key购买 nike

编辑:这个问题是针对已弃用的夏洛克 Action 栏的。现在应该改用 Android 支持库

我为我的 fragment 添加了一个名为 share 的操作栏菜单选项,该选项出现但未捕获选择事件

我是这样添加的

@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
MenuItem item = menu.add(0, 7,0, R.string.share);
item.setIcon(R.drawable.social_share).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}

试图在 fragmentfragment Activity 中都捕获它

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case 7:
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
startActivity(Intent.createChooser(share, "Share Text"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}

我在 onCreate() 中有 setHasOptionsMenu(true);

最佳答案

同样的问题也发生在我身上:

onMenuItemSelected events didn't get called in Fragment

搜google没找到解决办法,在FragmentActivity中加onMenuItemSelected方法也没解决。

最后引用http://developer.android.com/guide/topics/ui/actionbar.html解决

Note: If you added the menu item from a fragment, via the Fragment class's onCreateOptionsMenu callback, then the system calls the respective onOptionsItemSelected() method for that fragment when the user selects one of the fragment's items. However the activity gets a chance to handle the event first, so the system calls onOptionsItemSelected() on the activity before calling the same callback for the fragment.

这意味着只有在 Activity 的 onOptionsItemSelected() 中没有该菜单项处理程序时,才会调用 fragment 上的 onOptionsItemSelected()。

代码如下-----删除FragmentActivity上R.action.add的处理程序):

@Override
public boolean onOptionsItemSelected(MenuItem item) {

switch (item.getItemId()) {
case android.R.id.home:
popBackStack();
return true;
case R.id.action_search:
searchAction();
return true;
case R.id.action_logout:
userLogout();
return true;
//case R.id.action_add:
//return true;
default:
return super.onOptionsItemSelected(item);
}
}

R.action.add 在 Fragment 上的处理程序如下所示:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

Log.d("onOptionsItemSelected","yes");
switch (item.getItemId()) {
case R.id.action_add:
add();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

最后记得添加

    setHasOptionsMenu(true);

在 Fragment 的 onCreate 方法中

关于android - (已弃用) fragment onOptionsItemSelected 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15035861/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com