Android Popup Menu Tutorial

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 tutorial

Step 3.

In activity_main.xml layout file design your application.

Add following Controls:-

popup menu tutorial

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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.button);
        //create button event listener
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            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() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {

                        Toast.makeText(MainActivity.this,item.getTitle(),Toast.LENGTH_LONG).show();
                        return false;
                    }
                });
                //after menu item listener code end add this code.
                popmenu.show();
            }
        });
    }

Step 5. Final Output

popup menu tutorial

Post Your Comment