[android] Android custom dropdown/popup menu

How do I do a custom dropdown/popup menu anchored to a button?

I need it to work like the popup menu (anchored to a view), and do something when I click an item from the menu.

How do I add items to the menu by code, keeping menu's height and make it scrollable if there are more than 5 items. I don't need to add any images, just text.

enter image description here

This question is related to android drop-down-menu menu android-menu popupmenu

The answer is


First, create a folder named “menu” in the “res” folder.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"/>
    <item
        android:id="@+id/add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Add"/>
    <item
        android:id="@+id/edit"
        android:icon="@android:drawable/ic_menu_edit"
        android:title="Edit">
        <menu>
            <item
                android:id="@+id/share"
                android:icon="@android:drawable/ic_menu_share"
                android:title="Share"/>
        </menu>
    </item>

</menu>

Then, create your Activity Class:

public class PopupMenu1 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_menu_1);
    }

    public void onPopupButtonClick(View button) {
        PopupMenu popup = new PopupMenu(this, button);
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(PopupMenu1.this,
                        "Clicked popup menu item " + item.getTitle(),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        });

        popup.show();
    }
}

I know this is an old question, but I've found another answer that worked better for me and it doesn't seem to appear in any of the answers.

Create a layout xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:paddingStart="10dip"
    android:paddingEnd="10dip">

<ImageView
    android:id="@+id/shoe_select_icon"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_gravity="center_vertical"
    android:scaleType="fitXY" />

<TextView
    android:id="@+id/shoe_select_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="20sp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"/>

</LinearLayout>

Create a ListPopupWindow and a map with the content:

ListPopupWindow popupWindow;
List<HashMap<String, Object>> data = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
    map.put(TITLE, getString(R.string.left));
    map.put(ICON, R.drawable.left);
    data.add(map);
    map = new HashMap<>();
    map.put(TITLE, getString(R.string.right));
    map.put(ICON, R.drawable.right);
    data.add(map);

Then on click, display the menu using this function:

private void showListMenu(final View anchor) {
    popupWindow = new ListPopupWindow(this);

    ListAdapter adapter = new SimpleAdapter(
            this,
            data,
            R.layout.shoe_select,
            new String[] {TITLE, ICON}, // These are just the keys that the data uses (constant strings)
            new int[] {R.id.shoe_select_text, R.id.shoe_select_icon}); // The view ids to map the data to

    popupWindow.setAnchorView(anchor);
    popupWindow.setAdapter(adapter);
    popupWindow.setWidth(400);
    popupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    devicesAdapter.setSelectedLeftPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                case 1:
                    devicesAdapter.setSelectedRightPosition(devicesList.getChildAdapterPosition(anchor));
                    break;
                default:
                    break;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    devicesAdapter.notifyDataSetChanged();
                }
            });
            popupWindow.dismiss();
        }
    });
    popupWindow.show();
}

The Kotlin Way

fun showPopupMenu(view: View) {
    PopupMenu(view.context, view).apply {
                menuInflater.inflate(R.menu.popup_men, menu)
                setOnMenuItemClickListener { item ->
                    Toast.makeText(view.context, "You Clicked : " + item.title, Toast.LENGTH_SHORT).show()
                    true
                }
            }.show()
}

UPDATE: In the above code, the apply function returns this which is not required, so we can use run which don't return anything and to make it even simpler we can also remove the curly braces of showPopupMenu method.

Even Simpler:

fun showPopupMenu(view: View) = PopupMenu(view.context, view).run {
            menuInflater.inflate(R.menu.popup_men, menu)
            setOnMenuItemClickListener { item ->
                Toast.makeText(view.context, "You Clicked : ${item.title}", Toast.LENGTH_SHORT).show()
                true
            }
            show()
        }

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu What is the hamburger menu icon called and the three vertical dots icon called? Changing text color of menu item in navigation drawer How to get selected value of a dropdown menu in ReactJS Android custom dropdown/popup menu Creating a Menu in Python How to make a 3-level collapsing menu in Bootstrap? how to set active class to nav menu from twitter bootstrap How to make jQuery UI nav menu horizontal? Twitter Bootstrap add active class to li Adding a right click menu to an item

Examples related to android-menu

How to change option menu icon in the action bar? Android custom dropdown/popup menu How to change MenuItem icon in ActionBar programmatically How to change the background color of Action Bar's Option Menu in Android 4.2? How do I hide a menu item in the actionbar? Android, How to create option Menu "No resource identifier found for attribute 'showAsAction' in package 'android'"

Examples related to popupmenu

Android custom dropdown/popup menu