- PopupMenu — Всплывающее меню
- res/menu/popupmenu.xml
- Меню со значками (Kotlin)
- Программное добавление пунктов
- Popup menu android material
- About
- Popup Menu in Android With Example
- Example
- Step by Step Implementation
- Material Menus – Material Component For Android
- Types of menus
- Dropdown Menus
- Overflow menus
- Context menus
- Popup menus
- Adding icons on popup menus
- List popup window menus
- Exposed dropdown menus
- Popup menu android material
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 для второго примера.
Программное добавление пунктов
Повесим на новую кнопку возможность программного добавления новых пунктов меню.
Источник
Popup menu android material
Material Popup Menu
This library allows to create simple popup menus programmatically with a nice type-safe builder syntax in Kotlin. Menus can be divided into separate sections with optional headers and contain icons.
Download (from JCenter)
To create a popup menu with a single section from an anchor view:
To create a popup menu with 2 sections and a section title in the second one:
- Showing popup menus with a builder pattern
- Separator between popup menu sections
- Section headers
- Light and dark styles
- Custom view items
- Setting item label text color & icon color for each individual item
- Setting custom popup background color
- Customizing default popup style via theme attribute
- Adding additional offsets to where the dialog should be shown
- Keeping popup open after clicking on item
- Dimming background behind popup
- Customizing popup width, padding & offsets
- Displaying an icon at the end of each item which indicates a nested submenu
You can use your own layouts for displaying the items in each section alongside the default layouts provided by the library. E.g.:
To achieve the above you need to set labelColor and iconColor on each item in a section as shown here:
To change the popup background color you need to create a custom style and pass it under style to the popup builder above. E.g. to use the primary color you could define the style like this:
HTML documentation of the current version of the library is available here.
Third Party Bindings
You may now use this library with React Native via the module here
I want to use the library but I don’t know Kotlin
Kotlin is extremely easy to use if you already know Java. Check out the official documentation — it’s really great!
I have not migrated to AndroidX. Can I use this library?
If you’re still using legacy Android Support libraries you can use version 2.2.0. AndroidX is supported by default since 3.0.0.
Can I use this library on Jelly Bean?
Up to 3.4.0 minimum supported version was API 16 (Jelly Bean) so you can use that version. Since 4.0.0 minimum supported version is API 19 (Kitkat).
About
Shows Material popup menus grouped in sections & more
Источник
Popup Menu in Android With Example
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.
Источник
Material Menus – Material Component For Android
A menu displays a list of choices on a temporary surface. They appear when users interact with a button, action, or other control.
Before getting into details. Check out my other post on material design,
To work with material design, First, we need to add material design dependency.
Table of Contents
Types of menus
- Dropdown menus
- Exposed dropdown menus
Dropdown Menus
Dropdown menus display a list of options, triggered by an icon, button, or action. Their placement varies based on the element that opens them.
Based on the usage and design, dropdown menus are used in four different ways.
- Overflow menus
- Context menus
- Popup menus
- List popup window menus
Overflow menus
The menu which appears after tapping these 3 dots located in the action bar.
To create the overflow menu, First create a menu XML file.
option_menu.xml:
Then, inflate the menu XML layout on onCreateOptionsMenu.
in your MainActivity.kt:
Context menus
The context menu that appears when a TextView is long pressed.
First, create Textview in your activity_main.xml layout,
In your code, inflate the context menu layout in onCreateContextMenu.
Also, you can override the onContextItemSelected to handle context menu item click.
Popup menus
The popup menu shows when a button is clicked.
Create a button in activity_main.xml,
With the click of the button, we need to create a PopupMenu() and inflate the menu layout into the popup menu.
Also, you can add click listener for the popup menu by setting setOnMenuItemClickListener into the popup menu.
Adding icons on popup menus
Currently, there is no public API to add icons on popup menus. The following workaround is for API 21+, and uses library-only APIs, and is not guaranteed to work in future versions.
create a menu layout with icon,
List popup window menus
We can show the list items in popup menu using the ListPopupWindow() .
In code, First create a listPopupWindow with list of menu items.
Then, show the list popup menu on by clicking of the button.
Exposed dropdown menus
Exposed dropdown menus display the currently selected menu item above the list of options. the exposed dropdown menus behavior same as a spinner. So, this will be the best alternative for the spinners.
The exposed dropdown menu is implemented through the TextInputLayout.
in code, set the arrayAdapter into autoCompleteTextView.
In the item layout (list_item.xml):
To have an outlined variation of the exposed dropdown menu, set the style to @style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu:
Non-editable variation
Disable the user input in the AutoCompleteTextView to have a non editable variation of the menu by setting android:inputType=”none” on the AutoCompleteTextView.
Setting a default value
In order to have a pre-selected value displayed, you can call setText(CharSequence text, boolean filter) on the AutoCompleteTextView with the filter set to false.
Источник
Popup menu android material
Menus display a list of choices on temporary surfaces.
Contents
A menu displays a list of choices on a temporary surface. They appear when users interact with a button, action, or other control.
Before you can use Material menus, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.
A typical menu resource looks like this:
A typical exposed dropdown menu looks like this:
See the dropdown menus and exposed dropdown menus sections for detailed usage information.
Making menus accessible
Menus are readable by most screen readers, such as TalkBack. Text rendered in menus is automatically provided to accessibility services. Additional content labels are usually unnecessary.
Android’s exposed dropdown menu component APIs support both label text and helper text, which tell the user what information is requested for a menu. While optional, their use is strongly encouraged. For more information about this component’s accessibility, check out the text field’s a11y section.
Menus allow users to make a selection from multiple options. They are less prominent and take up less space than selection controls, such as a set of radio buttons.
There are two types of menus: 1. Dropdown menus (overflow, context, popup, and list popup window menus), 2. Exposed dropdown menus.
Dropdown menus display a list of options, triggered by an icon, button, or action. Their placement varies based on the element that opens them.
Dropdown menu examples
API and source code:
The following example shows an overflow menu.
The following example shows a context menu that appears when a TextView is pressed for a designated amount of time.
Alternatively, you can inflate a context menu in onCreateContextMenu (as with the overflow menu):
with a res/menu/context_menu.xml :
The following example shows a popup menu that displays when a button is clicked.
Adding icons to popup menus
Currently, there is no public API to add icons to popup menus. The following workaround is for API 21+, and uses library-only APIs, and is not guaranteed to work in future versions.
The following example shows a popup menu with icons.
List popup window menus
The following example shows a list popup window menu that appears when a button is clicked.
In the item layout res/layout/list_popup_window_item.xml :
Anatomy and key properties
The following are menu anatomy diagrams showing all possible elements:
- List item
- Leading icon
- Trailing icon
- Trailing text
- Container
- Divider
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Background | android:popupMenuBackground | N/A | ?attr/popupMenuBackground |
Color | N/A | N/A | ?attr/colorSurface |
Elevation | android:popupElevation | N/A | 3dp |
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Text label | android:title | getMenu().add getMenu().addSubMenu getMenu().getItem | N/A |
Typography | ?attr/textAppearanceLargePopupMenu ?attr/textAppearanceSmallPopupMenu | N/A | ?attr/textAppearanceBodyLarge |
Element | Theme attribute | Default value |
---|---|---|
Popup menus | ?attr/popupMenuStyle | @style/Widget.Material3.PopupMenu |
List popup window style | ?attr/listPopupWindowStyle | @style/Widget.Material3.PopupMenu.ListPopupWindow |
Context menus | ?android:contextPopupMenuStyle | @style/Widget.Material3.PopupMenu.ContextMenu |
Overflow menus | ?attr/actionOverflowMenuStyle | @style/Widget.Material3.PopupMenu.Overflow |
See the full list of styles and attrs.
Exposed dropdown menus
Exposed dropdown menus display the currently selected menu item above a list of options. Some variations can accept user-entered input.
Note: The exposed dropdown menu is implemented through the TextInputLayout . For detailed information on Material text fields and their usage, see the TextInputLayout documentation.
Exposed dropdown menu example
API and source code:
Note: MaterialComponentsViewInflater auto-inflates to when using Theme.Material3.* themes.
The following is an example of a filled exposed dropdown menu:
In the item layout ( list_item.xml ):
To use the exposed dropdown menu with an outlined text field, set the style to @style/Widget.Material3.TextInputLayout.OutlinedBox.ExposedDropdownMenu :
Non editable variation
For a non-editable menu, disable the user input in the AutoCompleteTextView by setting android:inputType=»none» on the AutoCompleteTextView .
Setting a default value
In order to have a pre-selected value displayed, you can call setText(CharSequence text, boolean filter) on the AutoCompleteTextView with the filter set to false .
Anatomy and key properties
The exposed dropdown menu is an AutoCompleteTextView within a TextInputLayout . It displays a dropdown menu below a text field.
- Text
- Container
- Label
- Selection/Input text
- Trailing icon
TextInputLayout attributes (container, label, trailing icon)
For all attributes that apply to the TextInputLayout , see the TextInputLayout documentation.
AutoCompleteTextView attributes (input text, dropdown menu)
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Input text | android:text | setText getText | @null |
Typography | android:textAppearance | setTextAppearance | ?attr/textAppearanceBodyLarge |
Input accepted | android:inputType | N/A | framework’s default |
Input text color | android:textColor | setTextColor getTextColors getCurrentTextColor | ?android:textColorPrimary |
Cursor color | N/A (color comes from the theme attr ?attr/colorControlActivated ) | N/A | ?attr/colorPrimary |
Dropdown menu container color | N/A | N/A | ?attr/colorSurface |
Dropdown menu elevation | android:popupElevation | N/A | 8dp |
Element | Style |
---|---|
Filled style | Widget.Material3.TextInputLayout.FilledBox.ExposedDropdownMenu |
Outlined style | Widget.Material3.TextInputLayout.OutlinedBox.ExposedDropdownMenu |
Filled dense | Widget.Material3.TextInputLayout.FilledBox.Dense.ExposedDropdownMenu |
Outlined dense | Widget.Material3.TextInputLayout.OutlinedBox.Dense.ExposedDropdownMenu |
Default style theme attribute: ?attr/textInputStyle
See the full list of styles and attrs.
Menus drawers support Material Theming which can customize color, typography and shape.
Menu theming examples
Popup, overflow, and list popup window menus support Material Theming which can customize typography.
API and source code:
The following example shows a menu with Material Theming.
Implementing menu theming
Use default style theme attributes, which affect all menus but do not affect other components:
Use a custom style instead of overriding ?attr/popupMenuBackground if you want to set a custom background for one type of menu:
Exposed dropdown menu theming example
Exposed dropdown menus support Material Theming which can customize color, typography, and shape.
Note: The exposed dropdown menu is implemented through the TextInputLayout . For detailed information on how Material text fields work, see the TextInputLayout documentation.
API and source code:
The following example shows filled and outlined exposed dropdown menu types with Material Theming.
Implementing exposed dropdown menu theming
Use default style theme attributes, styles and theme overlays which adds themes to all menus but does not affect other components:
or use the style in the layout, which affects only this menu:
Источник