Sunday, 6 November 2016

Pop-up Context Menu in Android

This tutorial is regarding the Pop-up context menu in android. With this tutorial will see how to create a simple pop-up menu.
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. Anchor text is the text relative to which your pop-up is visible.
The android.widget.PopupMenu is the direct subclass of java.lang.Object class.

1. Create a file as follows activity_main.xml:
This file will be created automatically when your project is being created.

<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" 
    tools:context=".MainActivity" >  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"
        android:layout_margin="16dp"  
        android:text="Show Popup" />  
  
</RelativeLayout> 

2. Create another class named popup_menu.xml:
This file is to be created inside the res/menu directory.

<menu xmlns:androclass="http://schemas.android.com/apk/res/android" >  
  
    <item  
        android:id="@+id/one"  
        android:title="Item_One"/>  
      
    <item  
        android:id="@+id/two"  
        android:title="Item_Two"/>  
        
    <item  
        android:id="@+id/three"  
        android:title="Item_Three"/>  
          
</menu> 

3. Now in your activity class named MainActivity.java do the following:

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

That's all. Your Pop-up menu is created.

No comments:

Post a Comment