Back to Browse

How to Create Android Popup Menu Programmatically and Handle Menu Items Click

12.2K views
Aug 2, 2020
16:08

Hi and welcome to another tutorial from CodingDemos :) In this tutorial, you will learn how to create Android popup menu or floating menu programmatically and click on menu items using setOnMenuItemClickListener. Here are the steps: 1- Open up Android Studio. 2- Using setOnClickListener to react to user taps on the button. openMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); 3- Inside the button onClick listener, declare the Popup menu. PopupMenu popupMenu = new PopupMenu(MainActivity.this, v); 4- Create a new menu file under Menu folder and initialize the menu items that you want to show inside the floating menu. popupMenu.getMenuInflater().inflate(R.menu.menu_popup, popupMenu.getMenu()); 5- Next, you need call setOnMenuItemClickListener to react when the user taps on the menu items. popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { return false; } }); 6- Inside onMenuItemClick, you need to check which menu item the user has taps based on the menu item ID using a Switch statement. switch (item.getItemId()) { case R.id.item_subscribe: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/c/codingdemos"))); return true; case R.id.item_website: startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.codingdemos.com"))); return true; default: return false; } 7- Finally, you need to show the popup menu like this. popupMenu.show(); 8- Now build and run the app to see the output. #androiddevelopment #androidprogramming #androidtutorial #androidstudio #androidstudiotutorial #java Links: Android photo Intent: https://developer.android.com/training/camera/photobasics#TaskPhotoView Website: https://www.codingdemos.com FaceBook: https://www.facebook.com/Codingdemos Introduction 00:00 Final output 00:30 Android Studio project introduction 01:47 Handle button click event 02:55 Android Popup Menu 03:25 Create menu items 04:35 Add items in Popup Menu 08:25 Clicking on Popup Menu items 09:35 Conclusion 15:30

Download

0 formats

No download links available.

How to Create Android Popup Menu Programmatically and Handle Menu Items Click | NatokHD