使用Fragment时无法显示弹出窗口

时间:2016-09-19 03:13:57

标签: android menu popupmenu

我在片段

中使用弹出菜单时遇到问题

这是我的弹出菜单功能

public void showPopupMenu(View view) {
        PopupMenu popup = new PopupMenu(context, view);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.dashboard_context_menu, popup.getMenu());
        popup.show();
    }

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

使用方法view时,不要忘记输入正确的showPopupMenu(View view)参数:

    public void showPopupMenu(View view) {
        PopupMenu popup = new PopupMenu(getActivity(), view); //use getActivity() in fragment

        popup.getMenuInflater().inflate(R.menu.dashboard_context_menu, popup.getMenu()); //optimize code ;)
        popup.show();
    }

答案 1 :(得分:0)

您正在使用Fragment,因此您必须从持有Fragment的Activity传递上下文。因此,您必须将代码context编辑为getActivity();

public void showPopupMenu(View view) {
    PopupMenu popup = new PopupMenu(getActivity(), view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.dashboard_context_menu, popup.getMenu());
    popup.show();
}

您可以修改showPopupMenu方法

public void showPopupMenu(Context context, View view) {
    PopupMenu popup = new PopupMenu(context, view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.dashboard_context_menu, popup.getMenu());
    popup.show();
}

调用方法

your_view.setOnClickListener(new OnClickListener() {
//your_view can be Button, TextView, EditText etc   
        @Override
        public void onClick(View v) {
            showPopupMenu(getActivity(),v);
        }
});