Android Custom Dropdown/popup Menu


Answer :

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"       android:paddingLeft="@dimen/activity_horizontal_margin"       android:paddingRight="@dimen/activity_horizontal_margin"       android:paddingTop="@dimen/activity_vertical_margin"       tools:context=".MainActivity" >        <Button           android:id="@+id/button1"           android:layout_width="wrap_content"           android:layout_height="wrap_content"           android:layout_alignParentLeft="true"           android:layout_alignParentTop="true"           android:layout_marginLeft="62dp"           android:layout_marginTop="50dp"           android:text="Show Popup" />    </RelativeLayout>   

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >        <item           android:id="@+id/one"           android:title="One"/>        <item           android:id="@+id/two"           android:title="Two"/>        <item           android:id="@+id/three"           android:title="Three"/>    </menu>   

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {       private Button button1;        @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          button1 = (Button) findViewById(R.id.button1);         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     } } 

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);  menu.getMenu().add("One"); menu.getMenu().add("Two"); menu.getMenu().add("Three");  menu.show(); 

Follow this link for creating menu programmatically.


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()         } 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable