Popup Menu Application

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.

Step 1.

Create new application with any name from file menu option.
File → New Project → Application name → select API → Add Blank Activity → Activity Name → finish

Step 2.

Open menu_main.xml file and Create menu item as need in application.
Go to app →res →menu →menu_main.xml file.

popup menu

Step 3.

In activity_main.xml layout file design your application.
Add following Controls:-

popup menu

Step 4.

Import Package and write following coding in MainActivity.java class file.

    import android.widget.Button;
    import android.widget.PopupMenu;
    import android.widget.Toast;
    public class MainActivity extends ActionBarActivity {

    Button btn;
    protected void onCreate(Bundle savedInstanceState) {

        btn = (Button) findViewById(R.id.button);
        //create button event listener
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            //inside button event listener create PopupMenu event listener
            PopupMenu popmenu = new PopupMenu(MainActivity.this,btn);
            popmenu.getMenuInflater().inflate(R.menu.menu_main, popmenu.getMenu());
            popmenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {

                        return false;
                //after menu item listener code end add this code.


Step 5. Final Output

popup menu
Advertisement here

Share this Page.