Android popup menu on CardView

When you go to the goole play store, you will see each app is presented in a CardView, and on the top right corner, there is a 3-dots icon which you can click on it and a popup menu will show up. This post will go through the steps for creating the popup menu on CardView in Android.

1. Create a layout file for in res/menu/popup_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add_to_itinerary"
        android:title="@string/menu_add_to_itinerary" />
    <item android:id="@+id/menu_remove_from_itinerary"
        android:title="@string/menu_remove_from_itinerary" />
</menu>

2. Go and find or create this 3-dots icon so you can use as the src for the ImageButton in the list item layout of the RecyclerView. For example:

<ImageButton
    android:id="@+id/ib_popup_menu"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="@null"
    android:src="@drawable/ic_action_navigation_more_vert"/>

3. Assume there is a listener interface such as this.

public interface PlaceInfoListener {
    void onPopupMenuClick(View view, int pos);
}

4. Assume this listener is being implemented by the Activity class that contains the RecyclerView, and it is passed into the RecyclerView Adapter.

5. In onBindViewHolder method of the RecyclerView Adapter, you can call this interface method when the ImageButton is clicked.

holder.ibPopupMenu.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        infoListener.onPopupMenuClick(view, listPosition);
    }
});

6. The implementation of the onPopupMenuClick method in the Activity class.

@Override
public void onPopupMenuClick(View view, int pos) {
    Place p = currentPlaces.get(pos);
    PopupMenu popup = new PopupMenu(this, view);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.popup_menu, popup.getMenu());
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
        	//do your things in each of the following cases
	        switch (item.getItemId()) {
	            case R.id.menu_add_to_itinerary:
	                return true;
	            case R.id.menu_remove_from_itinerary:
	                return true;
	            case R.id.menu_mark_as_visited:
	                return true;
	            default:
	                return false;
	        }
        }
    });
    popup.show();
}

References: 1, 2

Search within Codexpedia

Custom Search

Search the entire web

Custom Search