Reputation: 13
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
Upvotes: 1
Views: 1741
Reputation: 37404
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;
}
Upvotes: 2
Reputation: 226
For that problem actually I suggest you to manage the onclick from activity, you can create an interface that allows to propagate through the activity, is cleaner.
Upvotes: 0