wuck wuck - 1 month ago 9
Android Question

Popup menu in fragment does not appear

Fairly new to android, I'm currently having some difficulties implementing a

PopupMenu
on my
ImageButton
in a Fragment. There are no errors in the code, the emulator is able to build successfully but upon clicking the
ImageButton
, the popup menu does not show up.

OneFragment.java

public class OneFragment extends Fragment {

public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_one, container,false);

ImageButton popupButton = (ImageButton)rootview.findViewById(R.id.chineseTelevision);
popupButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

PopupMenu popupMenu = new PopupMenu(getActivity().getApplicationContext(), v);
popupMenu.inflate(R.menu.menu_main);
popupMenu.show();
}
});

return inflater.inflate(R.layout.fragment_one, container, false);
}
}


After applying Pavneet's solution (which is the right solution)

return rootview;


I stumbled onto another error,

android.view.InflateException: Binary XML file line #17: Failed to resolve attribute at index 6: TypedValue{t=0x3/d=0x486 "res/drawable/ic_menu_moreoverflow_material.xml" a=1 r=0x10803d6}


I found out that this error was caused android.support.v7.widget.PopupMenu.

This link has the solution but no explanation to why the widget caused the issue. Here Popup Menu in custom ListView

Answer

you need to return the rootview instead of new one

return inflater.inflate(R.layout.fragment_one, container, false);

so it should be

return rootview;

return inflater.inflate(R.layout.fragment_one, container, false); will create and return a new view instead of, the one you have created and hence the new one will not have any initialized popupmenu object inside it

so your code will be

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.fragment_one, container,false);

    ImageButton popupButton = (ImageButton)rootview.findViewById(R.id.chineseTelevision);

    popupButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

        PopupMenu popupMenu = new PopupMenu(getActivity().getApplicationContext(), v);
        popupMenu.inflate(R.menu.menu_main);
        popupMenu.show();

    }
  });
  return rootview;
}
Comments