片段的onOptionsItemSelected不会被调用 [英] Fragment's onOptionsItemSelected doesn't get called
问题描述
我的片段用特定的选项项目替换了父活动选项,但是当我单击该项目时,即使我已经覆盖了片段中的方法,也只有活动的 onOptionItemSelected
被调用.我想念什么吗?
My fragment replaces the parent Activity options with a specific option item but when I click on the item, only activity's onOptionItemSelected
gets called eventhough I've overridden the method inside Fragment. Am I missing something?
片段的方法:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d(TAG, "Fragment.onCreateOptionsMenu");
if (mPasteMode) {
menu.clear();
inflater.inflate(R.menu.contexual_paste, menu);
getActivity().getActionBar().setTitle("PasteMode");
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "Fragment.onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.context_action_paste:
Toast.makeText(getActivity(),
"It worked ",
Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
活动方法:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "MainActivitiy.onOptionsItemSelected");
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(this, "Action Refresh selected", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
Logcat输出:
MainActivity.onCreateOptionsMenu
Fragment.onCreateOptionsMenu
MainActivitiy.onOptionsItemSelected
那么我该如何调用片段的 onOptionsItemSelected
?
So how can I have the onOptionsItemSelected
of the fragment called?
推荐答案
您没有在活动方法中链接到超类.请让 onCreateOptionsMenu()
返回 super.onCreateOptionsMenu(menu)
,并让 onOptionsItemSelected()
返回 super.onOptionsItemSelected(item)
(正在处理的项目除外,该项目应返回 true
表示您已处理事件).
You are not chaining to the superclass in the activity methods. Please have onCreateOptionsMenu()
return super.onCreateOptionsMenu(menu)
, and have onOptionsItemSelected()
return super.onOptionsItemSelected(item)
(except for the item that you are handling, which should return true
to indicate that you have handled the event).
这篇关于片段的onOptionsItemSelected不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!