Android Popup Menu ExamplePopup 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.Android Popup Menu ExampleLet's see how to create popup menu in android.activity_main.xmlIt contains only one button.
File: 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> popup_menu.xmlIt contains three items as show below. It is created inside the res/menu directory.
File: 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> Activity classIt 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) { //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 } } Output: |
Android Popup Menu Example
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment