我在片段
中使用弹出菜单时遇到问题这是我的弹出菜单功能
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();
}
如何解决这个问题?
答案 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);
}
});