Try this:
popup_menu
<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/one"
android:title="One"
android:icon="@drawable:ic_launcher"/>
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
In your activity on button click add this:
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();//showing popup menu
}
});//closing the setOnClickListener method
Hope it helps :)
For menu icon to show add:
// Force icons to show
Object menuHelper;
Class[] argTypes;
try {
Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
fMenuHelper.setAccessible(true);
menuHelper = fMenuHelper.get(popup);
argTypes = new Class[] { boolean.class };
menuHelper.getClass().getDeclaredMethod("setForceShowIcon", argTypes).invoke(menuHelper, true);
} catch (Exception e) {
// Possible exceptions are NoSuchMethodError and NoSuchFieldError
//
// In either case, an exception indicates something is wrong with the reflection code, or the
// structure of the PopupMenu class or its dependencies has changed.
//
// These exceptions should never happen since we're shipping the AppCompat library in our own apk,
// but in the case that they do, we simply can't force icons to display, so log the error and
// show the menu normally.
Log.w("error", "error forcing menu icons to show", e);
popup.show();
return;
}