问题描述
我想用弹出来的动作栏菜单项。这一切就OK了,当我用这个在活动,但是当我切换到片段,我得到:
I want to use popup to a menu item in action bar. It's everything ok when I use this in the Activity but when I switch to fragment I get:
MenuPopupHelper cannot be used without an anchor
我的片段:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_filter:
createCategoriesPopupMenu(item);
return true;
case R.id.action_sort:
createSortPopupMenu(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void createSortPopupMenu(MenuItem item)
{
PopupMenu popup;
final View menuItemView = getView().findViewById(item.getItemId());
Log.wtf("d","item getitemid"+item.getItemId());
if (menuItemView == null)
{
Log.wtf("d","menuItemView==null view"+view.findViewById(item.getItemId()));
Log.wtf("d","menuItemView==null getAc"+getActivity().findViewById(item.getItemId()));
//final View searchItemView = getView().findViewById(R.id.action_search);
//popup = new PopupMenu(getActivity(), searchItemView);
}
popup = new PopupMenu(getActivity(), menuItemView);
Menu menu = popup.getMenu();
addSortMenuItems(menu);
popup.setOnMenuItemClickListener(new OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
onSortMenuItemClick(item);
return true;
}
});
popup.show();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.issues_list_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
控制台输出(断言):
console output(assert):
07-08 14:08:16.659:A / D(1677):项目getitemid2131165600 07-08
14:08:16.659:A / D(1677):menuItemView == NULL viewnull 07-08
14:08:16.659: A/d(1677): menuItemView==null viewnull 07-08
14:08:16.663:A / D(1677):menuItemView == NULL getAcnull
14:08:16.663: A/d(1677): menuItemView==null getAcnull
余did't忘记setHasOptionsMenu(真正的);在onCreateView()和视图
是 onCreateView充气布局()
I did't forgot setHasOptionsMenu(true); in onCreateView()and view
is inflated layout from onCreateView()
推荐答案
好吧,我找到解决方案,XML菜单文件项,我们要添加弹出,我们需要设置
Ok i found solution in xml menu file in item which we want to add popup we need to set
android:showAsAction="always"
becouse弹出仅适用于在没有菜单操作栏中的图标。还可以使用getActivity()。findView ...不是getView()。findView ...
becouse popup works only on icons in action bar not in menu. Also use getActivity().findView... not getView().findView...
这篇关于菜单弹出辅助离不开锚使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!