Android Option Menu In Kotlin

Menus are a common user interface component in many types of applications. The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app,  such as "Search," "Compose email," and "Settings."



Lets See How to Create Option Menu .

Creating an Options Menu


1. Menu XML .

Inside the res/menu/ create a xml file "menu_main.xml" .

file: : menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.tutorialsbuzz.androidoptionmenu.MainActivity">

    <item
        android:id="@+id/action_item1"
        android:orderInCategory="100"
        android:title="@string/action_item1"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_item2"
        android:icon="@mipmap/ic_launcher"
        android:orderInCategory="100"
        android:title="@string/action_item2"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_item3"
        android:orderInCategory="100"
        android:title="@string/action_item3"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_item4"
        android:orderInCategory="100"
        android:title="@string/action_item4"
        app:showAsAction="never" />
    
</menu>

2. XML Layout .

Add the app bar (also known as the action bar) and toolbar  widget to your xml layout .

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


3. Setup ActionBar
Inside the onCreate method call setSupportActionBar by passing toolbar reference .

setSupportActionBar(toolbar)

4. onCreateOptionsMenu .

Override the onCreateOptionsMenu callback inside your activity class and call inflater method on menuInflater object by passing main_menu.xml which is defined above .

 override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }


Handling click events


Override the onOptionsItemSelected callback of activity to handle click event of option menu .

override fun onOptionsItemSelected(item: MenuItem): Boolean {
 return when (item.itemId) {
  R.id.action_item1 -> {
    // handing on click of item with id action_item1
   true
  }

  R.id.action_item2 -> {
   // handing on click of item with id action_item2
   true
  }

  R.id.action_item3 -> {
    // handing on click of item with id action_item3
   true
  }

  R.id.action_item4 -> {
    // handing on click of item with id action_item4
   true
  }

  else -> super.onOptionsItemSelected(item)
 }
}


How Item's Should display in Action Bar


Using "showAsAction" attritube of item tag we can specify how the items of option menu should display in the Action Bar .
  • never : Never show this item in an action bar, show it in the overflow menu instead. Mutually exclusive with "ifRoom" and "always" .
  • ifRoom : Show this item in an action bar if there is room for it as determined by the system. Favor this option over "always" where possible. Mutually exclusive with "never" and "always".
  • always : Always show this item in an actionbar, even if it would override the system's limits of how much stuff to put there. This may make your action bar look bad on some screens. In most cases you should use "ifRoom" instead. Mutually exclusive with "ifRoom" and "never" .
  • withText : When this item is shown as an action in the action bar, show a text label with it even if it has an icon representation. 
  • collapseActionView : This item's action view collapses to a normal menu item. When expanded, the action view takes over a larger segment of its container.

SubMenu


To Create SubMenu Add Menu Tag inside Item Tag .

<item
  android:id="@+id/action_item1"
  android:orderInCategory="100"
  android:title="@string/action_item1"
  app:showAsAction="never">

 <menu>
  <item
    android:id="@+id/action_sub_item01"
    android:orderInCategory="100"
    android:title="@string/action_sub_item01"
    app:showAsAction="never" />

  <item
   android:id="@+id/action_sub_item02"
   android:orderInCategory="100"
   android:title="@string/action_sub_item02"
   app:showAsAction="never" />
 </menu>

</item>


Styling Option Menu 


You can customize the option menu by setting it to light and dark ,also you can change the background color , text color .

In the xml layout for Toolbar widget use the "app:popupTheme" to set the theme for option menu .
<com.google.android.material.appbar.AppBarLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:theme="@style/AppTheme.AppBarOverlay">

 <androidx.appcompat.widget.Toolbar
  android:id="@+id/toolbar"
  android:layout_width="match_parent"
  android:layout_height="?attr/actionBarSize"
  android:background="?attr/colorPrimary"
  app:popupTheme="@style/AppTheme.PopupOverlay" />

</com.google.android.material.appbar.AppBarLayout>

1. Light Theme

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />


2. Dark Theme

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Dark" />

3 Custom Styling


<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
 <item name="android:colorBackground">@color/colorAccent</item>
 <item name="android:textColorPrimary">#ffffff</item>
 <item name="android:textColorSecondary">#ffffff</item>
</style>


MainActivity



file : MainActivity.kt
package com.tutorialsbuzz.androidoptionmenu

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_item1 -> {
                showMessage(resources.getString(R.string.action_item1) + " clicked")
                true
            }

            R.id.action_item2 -> {
                showMessage(resources.getString(R.string.action_item2) + " clicked")
                true
            }

            R.id.action_item3 -> {
                showMessage(resources.getString(R.string.action_item3) + " clicked")
                true
            }

            R.id.action_item4 -> {
                showMessage(resources.getString(R.string.action_item4) + " clicked")
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showMessage(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}


Menu Related
  1. Option Menu
  2. Context Menu
  3. Popup Menu

No comments:

Post a Comment