Working with Popup Menu

Working with Popup Menu Example in Android

MainClass

package com.example.malik.test;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void showPopup(View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.popup_menu, popupMenu.getMenu());
PopupMenuEventHandler popupMenuEventHandler = new PopupMenuEventHandler(getApplicationContext());
popupMenu.setOnMenuItemClickListener(popupMenuEventHandler);
popupMenu.show();
}
}

 

MainXML

<?xml version=”1.0″ encoding=”utf-8″?>
<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=”com.example.malik.test.MainActivity”
android:id=”@+id/relative_layout”
>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Login”
android:id=”@+id/button”
android:layout_marginTop=”88dp”
android:layout_alignParentTop=”true”
android:layout_centerHorizontal=”true”
android:onClick=”showPopup”
/>
</RelativeLayout>

 

popup_menu XML

<?xml version=”1.0″ encoding=”utf-8″?>
<menu xmlns:android=”http://schemas.android.com/apk/res/android”>

<item android:id=”@+id/admin” android:title=”Login As Admin”></item>
<item android:id=”@+id/user” android:title=”Login As User”></item>

</menu>

 

PopupMenuEventHandler CLASS

package com.example.malik.test;

import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.widget.Toast;

/**
* Created by malik on 10/06/2016.
*/
public class PopupMenuEventHandler implements PopupMenu.OnMenuItemClickListener {
Context context;

public PopupMenuEventHandler(Context context) {
this.context = context;
}

@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.admin) {
Toast.makeText(context, “You select Admin”, Toast.LENGTH_SHORT).show();
return true;
} else if (item.getItemId() == R.id.user) {
Toast.makeText(context, “You select User”, Toast.LENGTH_SHORT).show();
return true;
}

return false;
}
}

 

Output :

pic

 

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.