Preap San
Preap San

Reputation: 115

Can't display popup while using Fragment

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

Answers (2)

user4696837
user4696837

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

or

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

Call the method

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

Upvotes: 0

W4R10CK
W4R10CK

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

Related Questions