Thursday, February 22, 2018

android kotlin - Menu and onCreateOptionsMenu example

Kotlin Menu & onCreateOptionsMenu
The Menu is a component of the native android SDK. The Menu is an android user interface component. Android SDK’s Menu API use to present user actions and other options in an Activity. The options menu is the primary menu for an activity where developers place the actions.

The following android kotlin tutorial will demonstrate how we can create an options Menu and place it in the android app user interface. This tutorial is written in Kotlin programming language with native android SDK tools.

Android SDK provides a standard XML format to define menu items. Instead, kotlin code developers should define the menu and its items in an XML menu resource. Then android developers can inflate the menu resource in the activity or fragment it as a Menu object.

Menu resource is easy to visualize and also easy to organize the menu structure in XML. The Menu resource separates content from Kotlin code. It allows us to create alternative menu configurations for different android platform versions, screen sizes, and other configurations.

The Menu resource XML content is built with several elements such as the menu, item, and group. The group is an invisible container for item elements. The group allows categorizing of menu items and shares properties such as active state and visibility. Menu ‘item’ element consists of several objects such as an id, title, icon, and showAsAction.

The onCreateOptionsMenu() method allows us to initialize the contents of the Activity’s standard options menu. In this method, developers inflate the XML Menu resource and display it in the toolbar. The onOptionsItemSelected() method allows developers to define the menu item’s click listener.

This android kotlin tutorial code is written in an android studio IDE. Copy the code into your android studio IDE and run it on an emulator to test how we implement an options menu in our tutorial. At the bottom of this kotlin tutorial, we display screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.*
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private lateinit var textView:TextView

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

        // Get the widgets reference from XML layout
        textView = findViewById(R.id.textView)

        // Get the support action bar
        val actionBar = supportActionBar

        // Set the action bar title
        actionBar?.title = "Kotlin Menu"
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu to use in the action bar
        val inflater = menuInflater
        inflater.inflate(R.menu.toolbar_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle presses on the action bar menu items
        when (item.itemId) {
            R.id.action_cut -> {
                textView.text = "Cut"
                return true
            }
            R.id.action_copy -> {
                textView.text = "Copy"
                return true
            }
            R.id.action_paste -> {
                textView.text = "Paste"
                return true
            }
            R.id.action_new -> {
                textView.text = "New"
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#DCDCDD">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Tap an item from action bar menu."
        android:textColor="#191970"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/menu/toolbar_menu.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">
    <item
        android:id="@+id/action_cut"
        android:title="Cut"
        app:showAsAction="ifRoom|withText"
        android:icon="@drawable/ic_action_cut"/>
    <item
        android:id="@+id/action_copy"
        android:title="Copy"
        app:showAsAction="always|withText"/>
    <item
        android:id="@+id/action_paste"
        android:title="Paste"
        app:showAsAction="ifRoom"/>
    <item
        android:id="@+id/action_new"
        android:title="New"
        app:showAsAction="ifRoom"/>
</menu>
More android examples