Android show popup menu

PopupMenu — Всплывающее меню

Начиная с Android 3.0, в системе появилась возможность создавать всплывающее меню, привязанное к элементу View. Меню реализовано в виде модального окна, которое отображается снизу от родителя меню или в другом месте, если места снизу недостаточно. PopupMenu не нужно путать с контекстным меню. У них разные задачи, хотя поведение весьма схоже. В новых версиях Android использование всплывающих меню предпочтительнее контекстных, которые можно считать устаревшим интерфейсом.

В Android 4.0 добавили новую функциональность, чтобы работать было проще. В частности, всплывающее меню можно получить из XML-файла, используя метод inflate(int), которому следует передать идентификатор ресурса меню. А до этого приходилось использовать отдельный класс MenuInflator с избыточным кодом.

Также появился слушатель PopupMenu.OnDismissListener для работы с закрытием меню. Он срабатывает либо, когда пользователь щёлкает на пункте меню и меню закрывается, либо пользователь щёлкает в другом месте экрана, и меню также закрывается.

Есть момент, который приводит к конфузу. Сейчас существует два класса с одинаковым именем из двух разных пакетов: android.widget и androidx.appcompat.widget (ещё были android.support.v7.widget.PopupMenu и android.support.v4.widget.PopupMenuCompat). Они практически одинаковы в применении, но в паре моментов поведение отличается.

Например, всплывающее меню из AndroidX может быть прокручиваемым. Когда я щёлкал на изображении, то на экран выводилось только два пункта, и для третьего пункта приходилось прокручивать меню.

Создать всплывающее меню очень просто. По сути мы повторяем шаги по созданию обычного меню. Сначала в ресурсах меню создадим нужный файл:

res/menu/popupmenu.xml

Я постарался использовать всевозможные варианты использования атрибутов, которые отвечают за вывод флажков, доступность и т.д. Есть и другие атрибуты, о которых читайте в документации.

Далее добавим на экран активности текстовую метку, кнопку и ImageView. При щелчке на каждом из этих компонентов мы будем выводить одинаковое всплывающее меню:

Осталось написать код.

Вам надо создать новый экземпляр PopupMenu, указав контекст активности и компонент, к которому будет привязано это меню. Далее загружаете меню из ресурсов и добавляете методы для обработки щелчков. Для отображения на экране вызывается метод show().

Запустив проект, вы можете щёлкать по любому элементу на форме и увидеть всплывающее меню.

Несмотря на то, что в XML мы указали значки, в реальности они не выводятся. В интернете можно найти примеры решения проблемы через программный код. В Android Q (API 29) можно сделать из коробки (см. пример ниже).

Меню со значками (Kotlin)

Напишем другой вариант примера на Kotlin и заставим систему выводить значки. Будем вызывать меню при нажатии на кнопку и выводить информацию в TextView через новый объект popupMenu2 из пакета android.widget, у которого есть специальный метод setForceShowIcon() для вывода значков на экран. И для сравнения оставим код из предыдущего примера.

Читайте также:  Android studio создать папку assets

Создадим новый файл меню res/menu/popup_menu.xml для второго примера.

Программное добавление пунктов

Повесим на новую кнопку возможность программного добавления новых пунктов меню.

Источник

In android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu , users can experience smooth and consistent experiences throughout the application. In android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:

  • Android Options Menu: Android Options Menu is a primary collection of menu items in an android application and useful for actions that have a global impact on the searching application.
  • Android Context Menu: Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and useful for elements that affect the selected content or context frame.
  • Android Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents to the view that invoked the menu and useful to provide an overflow of actions that related to specific content.

So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup window anchored to a View. The popup will be shown below the anchored View if there is room(space) otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it.

Example

In this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Working with the activity_main.xml file

In this step, we will add a button to the layout file and give it an id as clickBtn to it.

Источник

Android Popup Menu with Examples

In android, Popup Menu displays a list of items in a modal popup window that is anchored to the view. The popup menu will appear below the view if there is a room or above the view in case if there is no space and it will be closed automatically when we touch outside of the popup.

The android Popup Menu provides an overflow style menu for actions that are related to specific content.

Читайте также:  Брелок android что это такое

Following is the pictorial representation of using Popup Menu in our android applications.

In android, the Popup Menu provides an overflow of actions that are related to specific content and the actions in the popup menu won’t affect the corresponding content. The popup menu won’t support any item shortcuts and item icons.

In android, the Popup menu is available with API level 11 (Android 3.0) and higher versions. If you are using Android 3.0 +, the Popup Menu won’t support any item shortcuts and item icons in the menu.

Create Android Popup Menu in XML File

In android, to define the popup menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and add a new XML (menu_example) file to build the menu.

Following is the example of defining a menu in XML file (menu_example.xml).

xml version= «1.0» encoding= «utf-8» ?>
menu xmlns: android = «http://schemas.android.com/apk/res/android» >
item android :id= «@+id/mail»
android :icon= «@drawable/ic_mail»
android :title= «@string/mail»/>
item android :id= «@+id/upload»
android :icon= «@drawable/ic_upload»
android :title= «@string/upload»
android :showAsAction= «ifRoom»/>
item android :id= «@+id/share»
android :icon= «@drawable/ic_share»
android :title= «@string/share»/>
menu >

Once we are done with the creation of menu, we need to create a view element which anchored the menu.

Button
android :id= «@+id/btnShow»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Show Popup Menu»
android :onClick= «showPopup»/>

Now in our activity we need to implement showPopup method to show the popup menu.

Load Android Popup Menu from an Activity

To show the popup menu for the view, we need to instantiate Popup constructor and use MenuInflater to load the defined menu resource using MenuInflater.inflate() like as shown below.

public void showPopup(View v) <
PopupMenu popup = new PopupMenu( this , v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_example, popup.getMenu());
popup.show();
>

Handle Android Popup Menu Click Events

To perform an action when the user selects a menu item, we need to implement the PopupMenu.OnMenuItemClickListener interface and register it with our PopupMenu by calling setOnMenuItemclickListener(). When the user selects an item, the system calls the onMenuItemClick() callback in your interface.

Following is the example of handling a popup menu item click event using onMenuItemClick().

public void showMenu(View v) <
PopupMenu popup = new PopupMenu( this , v);
popup.setOnMenuItemClickListener( this );
popup.inflate(R.menu.actions);
popup.show();
>

@Override
public boolean onMenuItemClick(MenuItem item) <
switch (item.getItemId()) <
case R.id.archive:
archive(item);
return true ;
case R.id.delete:
delete(item);
return true ;
default :
return false ;
>
>

Note: If you are using Android 3.0 +, the Popup Menu won’t support any item shortcuts and item icons in the menu.

Android Popup Menu Example

Following is the example of implementing a Popup Menu in the android application.

Create a new android application using android studio and give names as PopupMenuExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Читайте также:  Андроид авто не работает тачскрин

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :orientation= «vertical» >

Button
android :id= «@+id/btnShow»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Show Popup Menu»
android :layout_marginTop= «200dp» android :layout_marginLeft= «100dp»/>
LinearLayout >

If you observe above code we created a one Button control in XML Layout file to show the popup menu when we click on Button.

In android, to define the popup menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and add a new XML (popup_menu.xml) file to build the menu.

Now open newly created xml (popup_menu.xml) file and write the code like as shown below.

xml version= «1.0» encoding= «utf-8» ?>
menu xmlns: android = «http://schemas.android.com/apk/res/android» >
item android :id= «@+id/search_item»
android :title= «Search»/>
item android :id= «@+id/upload_item»
android :title= «Upload»/>
item android :id= «@+id/copy_item»
android :title= «Copy»/>
item android :id= «@+id/print_item»
android :title= «Print»/>
item android :id= «@+id/share_item»
android :title= «Share»/>
item android :id= «@+id/bookmark_item»
android :title= «BookMark»/>
menu >

Once we are done with the creation of the menu, we need to load this menu XML resource from our activity by instantiating a Popup constructor, for that open main activity file MainActivity.java from \java\com.tutlane.popupmenuexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.popupmenuexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener <
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btn = (Button) findViewById(R.id. btnShow );
btn.setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
PopupMenu popup = new PopupMenu(MainActivity. this , v);
popup.setOnMenuItemClickListener(MainActivity. this );
popup.inflate(R.menu. popup_menu );
popup.show();
>
>);
>
@Override
public boolean onMenuItemClick(MenuItem item) <
Toast.makeText( this , «Selected Item: » +item.getTitle(), Toast. LENGTH_SHORT ).show();
switch (item.getItemId()) <
case R.id. search_item :
// do your code
return true ;
case R.id. upload_item :
// do your code
return true ;
case R.id. copy_item :
// do your code
return true ;
case R.id. print_item :
// do your code
return true ;
case R.id. share_item :
// do your code
return true ;
case R.id. bookmark_item :
// do your code
return true ;
default :
return false ;
>
>
>

If you observe above code we are trying to show popup menu on Button click, loaded defined menu resource using Popup.inflate() and implement popup menu items click event.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android Popup Menu Example

When we run above example using an android virtual device (AVD) we will get a result like as shown below.

This is how we can create Popup Menu in android applications to handle global actions.

Источник

Оцените статью