如果没有锚点,则无法使用菜单弹出助手

时间:2014-07-08 14:15:38

标签: java android android-activity android-fragments

我想在操作栏中使用弹出菜单项。当我在Activity中使用它时,一切都很好但是当我切换到片段时,我得到:

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);
}

控制台输出(断言):

  

07-08 14:08:16.659:A / d(1677):item getitemid2131165600 07-08

     

14:08:16.659:A / d(1677):menuItemView == null viewnull 07-08

     

14:08:16.663:A / d(1677):menuItemView == null getAcnull

我没有忘记setHasOptionsMenu(true);在onCreateView()中 并且view是来自onCreateView()

的夸大布局

2 个答案:

答案 0 :(得分:13)

好的,我在项目中的xml菜单文件中找到了解决方案,我们要添加需要设置的弹出窗口

android:showAsAction="always"

因为弹出窗口仅适用于操作栏中的图标而非菜单中的图标。还可以使用getActivity()。findView ...而不是getView()。findView ...

答案 1 :(得分:0)

您可以更改

final View menuItemView = getView().findViewById(item.getItemId());

final View menuItemView = getActivity().findViewById(item.getItemId());