Popup menu android item

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() для вывода значков на экран. И для сравнения оставим код из предыдущего примера.

Создадим новый файл меню 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.

Читайте также:  Чтения комиксов для android

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.

Источник

Apps often need to provide the user with a consistent experience for executing actions that are contextually specific. The most common actions for an activity live on the default Action Bar but actions that are more specific to an item or element can be displayed contextually using menus and popups. In addition to menus, apps often need to display popup overlays that contain informational content. This guide covers how to manage menus and popups within your Android apps.

In modern Android apps, there are a few mechanisms for displaying secondary content or actions related to an Activity:

  • Contextual Action Modes — An «action mode» which is enabled when a user selects an item. Upon the item selection, the actionbar switches to a contextual mode that presents relevant actions.
  • PopupMenu — A modal menu that is anchored to a particular view within an activity. The menu appears below that view when it is selected. Used to provide an overflow menu that allows for secondary actions on an item.
  • PopupWindow — A simple dialog box that gains focus when appearing on screen. It is used to display additional information on screen and is simpler but less flexible than a DialogFragment.
  • DialogFragment — A fully customizable dialog overlay that appears ontop of the activity and can contain arbitrary content as defined within the fragment. This is the most flexible but also the heaviest approach to displaying overlay content.

Let’s take a look at each one of these.

Contextual Action Modes can be enabled when a user selects or focuses on any item. Upon the item selection, the ActionBar switches to a contextual mode that presents relevant actions for said item.

Important actions related to the view item should be presented by constructing these contextual action modes whenever possible. The action mode is typically presented upon long click of a view or by selecting a checkbox within the activity.

Let’s take a look at how to create a contextual action mode for a view which will be presented when a view is long clicked. First, let’s define a menu XML file to be displayed in a res/menu/actions_textview.xml file:

Next, let’s define a ActionMode.Callback which will be manage the behavior of our contextual action menu:

Now that we have an ActionMode we can enable for any view (i.e TextView) or AdapterView (such as a ListView) which will display a contextual action bar for that element.

To activate the contextual action mode defined above for a simple TextView, we just need to attach the OnLongClickListener for the view and then trigger the action mode using startActionMode :

That’s all and now you have a TextView that upon long clicking will reveal the contextual action bar menu as show below:

We can also enable contextual menus for ListView items as well. This is as simple as setting the setOnItemLongClickListener property for the list items and then presenting the action mode. Given the same action mode defined the previous sections, we can apply the mode to items with:

This will trigger the contextual action menu whenever a list item is long-clicked. Notice that we also store the currentListItemIndex so we can act directly on the correct item after an action is selected. For example, the modeCallback might have a onActionItemClicked defined as:

This will result in the following after being defined correctly:

Using this approach we can easily allow users to act on items within a list. Note that in certain cases we may want to also support batch modes where more then one item can be affected by a contextual action. In that case, we need to use a MultiChoiceModeListener as the ActionMode as explained in the official menus docs.

A modal menu that is anchored to a particular view within an activity and the menu appears below that view when displayed. Used to provide an overflow menu that allows for secondary actions on an item.

Читайте также:  Живые обои с волками для андроид

Note that if the items change the selected content, consider using the «Contextual Action Mode» explained above. Instead, use this for actions that relate to the content, for example triggering a reply to a message.

Defining a PopupMenu for a view is as simple as constructing the PopupMenu object and then defining the menu XML that you would like to display. For example, if we wanted to present a popup menu for filtering items when a button was clicked, first we define the menu XML for that button in res/menu/popup_filters.xml :

Next, we define a click handler for the button that displays the PopupMenu :

With that setup, whenever the button is pressed, the menu will be displayed and a different action will be taken based on the item selected. Here’s the result:

In addition to contextual action modes and popup menus, there are also a more customizable PopupWindow concept. PopupWindow is a floating content container that appears over the current activity like a simplified DialogFragment that is less flexible but easier to implement. Popups are usually used to show some additional information or something user wants to know after an event takes place.

To display a PopupWindow , let’s first download a background to use for the popup within res/drawable/popup_bg.9.png . The background is a nine-patch image which will be used as the background for the popup content.

Next, let’s define an arbitrary XML layout file which will be displayed within the popup at res/layout/popup_content.xml :

Now, we have the background and the content layout defined so we can setup the popup to display when a button is clicked with:

Finally, we need to define the displayPopupWindow method to actually construct and display the window based on our content area and background image:

The result of this is a dismissable popup window with our content and which looks like:

Read more details on the PopupWindow tutorial. You might also want to check out this extended DismissablePopupWindow for a simple re-usable popup that had a dismiss button embedded within the window.

Prior to Android 3.0, there were several other relevent menu strategies which are now discouraged. The strategies that have been deprecated in modern apps are listed below:

  • Options Menu — This was a menu that appeared when a hardware «menu button» was pressed. This menu button has been deprecated and should no longer be used in modern apps. You can read more in the Creating an Options Menu official guide.
  • Floating Context Menu — This was a contextual menu that appeared to float above the activity with a list of menu items to select. This approach is deprecated in favor of the aforementioned Contextual Action Mode in modern apps. See this tutorial for another look at the deprecated floating context approach.

In certain cases, we may want to group menu items together within a menu XML. To group menu items simply wrap them in a group node in the menu xml:

Check out more details in the Menu Groups official docs which shows you how to create «checkable» items as well.

Источник

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.

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 >

Читайте также:  Tele2 личный кабинет android

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.

Источник

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