Popup Menu

android_learners_hub
android_learners_hub

Previous                                                                                                                                               Next

Popup Menu in Android

When we simply click a view (suppose a textview) that contain popup menu then, a list of veritcally arranged items in modal popup window is displayed. The popup will be shown below the anchored View (view on which we set popup menu) if there is room (space) otherwise above the View.Popup menu will be dismissed if we click outside it. You can listen dismiss event using PopupMenu.OnDismissListener.It is a callback interface used to notify the application that the menu has closed.  In android, the Popup menu is available with API level 11 (Android 3.0) and higher versions. 
It is used for creating a drop-down similar to Spinner but it will retain a persistent selection, for storing overflow content that belongs to related actions and providing a second part of a command sentence(ex.  In contacts app when we select "All Contacts" then a popup menu display that shows  (second command)  SIM 1, SIM2 as menu items). The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

Constructor

Constructor Description
1.public PopupMenu (Context context, View anchor) Constructor to create a new popup menu with an anchor view.
2.PopupMenu(Context context, View anchor, int gravity) Constructor to create a new popup menu with an anchor view and alignment gravity.
3.PopupMenu(Context context, View anchor, int gravity, int popupStyleAttr, int popupStyleRes) It is used to create a new popup menu with a specific style.

Public Methods

Method Description
1. void dismiss() It is used to dismiss the popup menu. It is added in API level 11.
2. void show() This method is used to show the menu popup anchored to the view specified during  construction. It is introduced in API level 11.
3. void inflate(int menuRes)  Inflate a menu resource into this PopupMenu. This is equivalent to calling popupMenu.getMenuInflater().inflate(menuRes, popupMenu.getMenu()).It is added in API level 14.
4.MenuInflater getMenuInflater(); It is a MenuInflater that can be used to inflate menu items from XML into the menu returned by getMenu().It is added in API level 11.
5.getMenu () Returns the Menu associated with this popup. Populate the returned Menu with items before calling show().It is added in API level 11.
6.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener listener)  This method is used to set a listener that will be notified when the user selects an item from the popup menu. It is added in API level 11.
7.void setOnDismissListener (PopupMenu.OnDismissListener listener)  This method is used to set a listener that will be notified when this menu is dismissed. It is added in API level 14.

Android Popup Menu Example

Let's see how to create popup menu in android.

In android, to define the popup menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and then, create a file in it to create menu or menu items.

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

<item
android:id="@+id/popup_1"
android:title="Import to Google Drive" />
<item
android:id="@+id/popup_2"
android:title="Favourites " />
<item
android:id="@+id/popup_3"
android:checkable="true"
android:title="SIM card 1" />
<item
android:id="@+id/popup_4"
android:checkable="true"
android:checked="true"
android:title="SIM card 2" />

</menu>
In activity_main.xml file I will create a Textview on the top of listview. When user click Textview it will show popup menu. 

Code for 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"
tools:context=".MainActivity"
android:orientation="vertical">

<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#C59169"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme" />

<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#4FCCBD5C"
android:text="All Contacts"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="#FF000000"/>

<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#C59169" />
</LinearLayout>

Now, to displays the popup menu we first get the reference of the Textview and initialize it then, set onclick listener to the listview (view) . Secondly, in the body of onclick listener we have to pass showPopup() method. In showPopup() method we will create instance of PopupMenu and to perform an action (Handling click events) when the user selects a menu item we have to register OnMenuItemClickListener with the instance of Popup menu. At last to show the menu popup  we will use show() method.

Code for MainActivity.java
package com.example.menu_android;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare the toolbar and give the toolbar the ability to have those options menu show up
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

//Referencing and Initializing List View
ListView list=findViewById(R.id.list_view);
String[] listitem={"A","Amandeep","Anchal","Ankita","Amritpreet","B","Babita","Bableen","Baby","C","Cherry","Chetan","Charanjeet"};
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1,android.R.id.text1,listitem);
list.setAdapter(adapter);
// Referencing and Initializing text View
TextView text_pop=findViewById(R.id.text);
// set on click listener on text View
text_pop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopup(v);
}
});

}
public void showPopup(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(this, v);
//Inflating the Popup using xml file
getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
//showing popup menu
popup.show();
}
After executing above code we will get following output:-

Output of menu popup

Output when we click on Import to google drive


Related Topics:

android_learners_hub


Comments