Как создать меню выбора параметров Kotlin Android

Меню параметров Android (Options Menu) в Kotlin — это набор пунктов меню для действия. Меню параметров позволяет размещать действия, которые глобально влияют на приложение.

Меню параметров создается путем переопределения функции onCreateOptionsMenu(). Ресурс меню наполняется и вызывается метод inflate() класса MenuInflater. Чтобы воздействовать на элементы меню, переопределите функцию onOptionsItemSelected().

Пример меню Kotlin Android Options

В этом примере мы добавим элементы меню параметров на панель действий. При нажатии на меню отображаются пункты меню параметров, над которыми мы можем выполнить соответствующее действие.

Создайте проект Android и выберите Basic Activity. Это действие автоматически генерирует коды для пункта меню и панели инструментов.

Activity_main.xml

Добавьте следующий код в файл activity_main.xml в каталоге макета. Этот код генерируется автоматически при создании Basic Activity.

<?xml version="1.0" encoding="utf-8"?>  
<android.support.design.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="example.javatpoint.com.kotlinoptionsmenu.MainActivity">  
  
    <android.support.design.widget.AppBarLayout  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:theme="@style/AppTheme.AppBarOverlay">  
  
        <android.support.v7.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" />  
  
    </android.support.design.widget.AppBarLayout>  
  
    <include layout="@layout/content_main" />  
  
</android.support.design.widget.CoordinatorLayout>

content_main.xml

Добавьте следующий код в файл content_main.xml в каталоге макета. В этом макете вы можете разместить свои компоненты пользовательского интерфейса.

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.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:layout_width="match_parent"  
    android:layout_height="match_parent"  
    app:layout_behavior="@string/appbar_scrolling_view_behavior"  
    tools:context="example.javatpoint.com.kotlinoptionsmenu.MainActivity"  
    tools:showIn="@layout/activity_main">  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Hello World!"  
        app:layout_constraintBottom_toBottomOf="parent"  
        app:layout_constraintLeft_toLeftOf="parent"  
        app:layout_constraintRight_toRightOf="parent"  
        app:layout_constraintTop_toTopOf="parent" />  
  
</android.support.constraint.ConstraintLayout>

strings.xml

Добавьте следующий код в файл strings.xml.

<resources>  
    <string name="app_name">Kotlin OptionsMenu</string>  
    <string name="action_settings">Settings</string>  
    <string name="action_share">Share</string>  
    <string name="action_exit">Exit</string>  
</resources>

Добавьте следующий код в файл menu_main.xml в каталоге меню. Добавьте тег элемента, который создает элемент меню для меню параметров.

<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="example.javatpoint.com.kotlinoptionsmenu.MainActivity">  
    <item  
        android:id="@+id/action_settings"  
        android:orderInCategory="100"  
        android:title="@string/action_settings"/>  
    <item  
        android:id="@+id/action_share"  
        android:title="@string/action_share"  
        app:showAsAction="never"/>  
    <item  
        android:id="@+id/action_exit"  
        android:title="@string/action_exit"  
        app:showAsAction="never"/>  
</menu>

MainActivity.kt

Добавьте следующий код в класс MainActivity.kt. В этом классе мы переопределяем функцию onCreateOptionsMenu() и вызываем метод inflate() класса MenuInflater, который расширяет меню и добавляет элементы на панель действий. Чтобы выполнить действие над каждым элементом опций, меню переопределяет функцию onOptionsItemSelected().

package example.javatpoint.com.kotlinoptionsmenu 
 
import android.os.Bundle 
import android.support.v7.app.AppCompatActivity 
import android.view.Menu 
import android.view.MenuItem 
import android.widget.Toast 
 
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_settings -> { 
                Toast.makeText(applicationContext, "click on setting", Toast.LENGTH_LONG).show() 
                true 
            } 
            R.id.action_share ->{ 
                Toast.makeText(applicationContext, "click on share", Toast.LENGTH_LONG).show() 
                return true 
            } 
            R.id.action_exit ->{ 
                Toast.makeText(applicationContext, "click on exit", Toast.LENGTH_LONG).show() 
                return true 
            } 
            else -> super.onOptionsItemSelected(item) 
        } 
    } 
} 

Вывод:

Меню параметров Kotlin AndroidМеню Kotlin Android - вывод

Вывод

Создание меню параметров с использованием изображений на панели действий

Мы также можем отобразить меню параметров в виде изображений на панели действий. Чтобы установить изображение в меню параметров, добавьте атрибут значка в тег элемента, как показано ниже.

<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="example.javatpoint.com.kotlinoptionmenu.MainActivity">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    android:icon="@android:drawable/btn_star" />
<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    app:showAsAction="ifRoom"
    android:icon="@drawable/shareimage"/>
<item
    android:id="@+id/action_exit"
    android:title="@string/action_exit"
    app:showAsAction="ifRoom"
    android:icon="@drawable/exitimage"/>
</menu>

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