Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu.
The android.widget.PopupMenu is the direct subclass of java.lang.Object class.
Android Popup Menu Example
Let's see how to create popup menu in android.
activity_main.xml
It contains only one button.
File: activity_main.xml
- <RelativeLayout xmlns:androclass="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>
popup_menu.xml
It contains three items as show below. It is created inside the res/menu directory.
File: poupup_menu.xml
- <menu xmlns:androclass="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>
Activity class
It displays the popup menu on button click.
File: MainActivity.java
- package com.javatpoint.popupmenu;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.PopupMenu;
- import android.widget.Toast;
- public class MainActivity extends Activity {
- 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) {
-
- PopupMenu popup = new PopupMenu(MainActivity.this, button1);
-
- popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
-
-
- 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();
- }
- });
- }
- }
Output:
No comments:
Post a Comment