activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.androidsimplifycodes.example.MainActivity">
<Button
android:id="@+id/btnPopUpMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Popup Menu"
android:textColor="@android:color/black"
android:textStyle="bold" />
</LinearLayout>
For the icons right click on drawable folder and select New->Vector Asset then after added required icons.
pop_up_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_phone"
android:icon="@drawable/ic_call"
android:title="Phone" />
<item
android:id="@+id/action_mail"
android:icon="@drawable/ic_post"
android:title="Mail" />
<item
android:id="@+id/action_add_to_calender"
android:icon="@drawable/ic_calendar"
android:title="Calender" />
</menu>
MainActivity.java
package com.androidsimplifycodes.example;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
protected Context context;
protected Button btnPopUpMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
context = MainActivity.this;
initView();
btnPopUpMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(context, view);
popupMenu.getMenuInflater().inflate(R.menu.pop_up_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_mail:
Toast.makeText(context, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.action_phone:
Toast.makeText(context, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.action_add_to_calender:
Toast.makeText(context, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
MenuPopupHelper menuHelper = new MenuPopupHelper(context, (MenuBuilder) popupMenu.getMenu(), view);
menuHelper.setForceShowIcon(true);
menuHelper.show();
}
});
}
private void initView() {
btnPopUpMenu = (Button) findViewById(R.id.btnPopUpMenu);
}
}
Output :