Reputation: 115
I have problem when I use the popup menu in fragment
this is my popup menu function
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();
}
how to solve this problems?
Upvotes: 0
Views: 90
Reputation:
You are using Fragment
so you have to pass context from Activity which holding the Fragment
. So you have to edit code context
to 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();
}
You can edit showPopupMenu
Method
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);
}
});
Upvotes: 0
Reputation: 5550
Don't forget to put proper view
argument while using method 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();
}
Upvotes: 1