Sitemap
Howtodoandroid

best android developers medium publication focused on beginners to learn the android concepts very easily. In this publication having android examples that explained in detail.

Material Menus — Material Component For Android

5 min readMar 23, 2021

--

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. Checkout my other post on material design,

To work with material design, First we need to add material design dependency.

implementation ‘com.google.android.material:material:1.3.0’

Types of menus

  1. Dropdown menus
  2. Exposed dropdown menus
Types of 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.

  1. Overflow menus
  2. Context menus
  3. Popup menus
  4. List popup window menus

Overflow menus

Press enter or click to view image in full size
Overflow menus design
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:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/option_1"
android:title="Home" />
<item android:id="@+id/option_2"
android:title="Settings" />

<item android:id="@+id/option_3"
android:title="Logout" />
</menu>

Then, inflate the menu XML layout on onCreateOptionsMenu.

in your MainActivity.kt:

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.option_menu, menu)
return true
}

Context menus

Press enter or click to view image in full size
Context Menus design
Context menus

The context menu that appears when a TextView is long pressed.

Get Velmurugan Murugesan’s stories in your inbox

Join Medium for free to get updates from this writer.

First, create Textview in your activity_main.xml layout,

<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="@string/lorem_ipsum"
android:padding="8dp"/>

In your code, inflate the context menu layout in onCreateContextMenu.

override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
super.onCreateContextMenu(menu, v, menuInfo)
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.option_menu, menu)
}

Also, you can override the onContextItemSelected to handle context menu item click.

override fun onContextItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.home -> {
// Respond to context menu home click.
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show()
true
}
R.id.settings -> {
// Respond to context menu settings click.
true
}
R.id.logout -> {
// Respond to context menu logout click.
true
}
else -> super.onContextItemSelected(item)
}
}

Popup menus

The popup menu shows when a button is clicked.

Press enter or click to view image in full size
Popup Menus design
Popup menus

Create a button in activity_main.xml,

<Button
android:id="@+id/showMenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Menu"
android:visibility="visible"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>

With the click of the button, we need to create a PopupMenu() and inflate the menu layout into the popup menu.

activityMainBinding.showMenu.setOnClickListener {
val popup = PopupMenu(this, it)
popup.menuInflater.inflate(R.menu.option_menu, popup.menu)

popup.setOnMenuItemClickListener { menuItem: MenuItem ->
// Respond to menu item click.
return@setOnMenuItemClickListener true
}
popup.setOnDismissListener {
// Respond to popup being dismissed.
}
// Show the popup menu.
popup.show()
}

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.

Press enter or click to view image in full size
Popup menus with icon design
Popup menus with icon

create a menu layout with icon,

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/home"
android:icon="@drawable/ic_baseline_home_24"
android:title="Home" />
<item android:id="@+id/settings"
android:icon="@drawable/ic_baseline_settings_24"
android:title="Settings" />

<item android:id="@+id/logout"
android:icon="@drawable/ic_baseline_exit_to_app_24"
android:title="Logout" />
</menu>

In code:

activityMainBinding.showMenu.setOnClickListener {
val popup = PopupMenu(this, it)
popup.menuInflater.inflate(R.menu.option_menu, popup.menu)
if (popup.menu is MenuBuilder) {
val menuBuilder = popup.menu as MenuBuilder
menuBuilder.setOptionalIconsVisible(true)
for (item in menuBuilder.visibleItems) {
val iconMarginPx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, ICON_MARGIN.toFloat(), resources.displayMetrics)
.toInt()
if (item.icon != null) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
item.icon = InsetDrawable(item.icon, iconMarginPx, 0, iconMarginPx,0)
} else {
item.icon =
object : InsetDrawable(item.icon, iconMarginPx, 0, iconMarginPx, 0) {
override fun getIntrinsicWidth(): Int {
return intrinsicHeight + iconMarginPx + iconMarginPx
}
}
}
}
}
}
popup.show()
}

List popup window menus

We can show the list items in popup menu using the ListPopupWindow() .

Press enter or click to view image in full size
List popup window menu design
List popup window menu

In code, First create a listPopupWindow with list of menu items.

val listPopupWindow = ListPopupWindow(this, null, R.attr.listPopupWindowStyle)
// Set button as the list popup's anchor
listPopupWindow.anchorView = activityMainBinding.showMenu
// Set list popup's content
val items = listOf("List Item 1", "List Item 2", "List Item 3")
val adapter = ArrayAdapter(this, R.layout.list_item, items)
listPopupWindow.setAdapter(adapter)
// Set list popup's item click listener
listPopupWindow.setOnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
// Respond to list popup window item click.
// Dismiss popup.
listPopupWindow.dismiss()
}

Then, show the list popup menu on by clicking of the button.

activityMainBinding.showMenu.setOnClickListener {
listPopupWindow.show()
}

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.

Press enter or click to view image in full size
Exposed dropdown menu design
Exposed dropdown menus

In the layout:

<com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputLayout"
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:hint="Select city">

<AutoCompleteTextView
android:id="@+id/menuAutocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

</com.google.android.material.textfield.TextInputLayout>

in code, set the arrayAdapter into autoCompleteTextView.

val items = listOf("Chennai", "Delhi", "Mumbai", "Pune")
val adapter = ArrayAdapter(this, R.layout.list_item, items)
activityMainBinding.menuAutocomplete.setAdapter(adapter)

In the item layout ( list_item.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:ellipsize="end"
android:maxLines="1"
android:padding="16dp"
tools:text="List "
android:textAppearance="?attr/textAppearanceSubtitle1" />

To have an outlined variation of the exposed dropdown menu, set the style to @style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu:

Press enter or click to view image in full size
Exposed dropdown menu with outlined style
Exposed dropdown menu with outlined style

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.

<AutoCompleteTextView
android:id="@+id/menuAutocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
/>

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.

That’s it. Thank you for reading.

Originally published at https://howtodoandroid.com on March 23, 2021.

--

--

Velmurugan Murugesan
Velmurugan Murugesan

Written by Velmurugan Murugesan

Lead Android Engineer @htcindia | @github contributor | Blog writer @howtodoandroid | Quick Learner

Howtodoandroid
Howtodoandroid

Published in Howtodoandroid

best android developers medium publication focused on beginners to learn the android concepts very easily. In this publication having android examples that explained in detail.