In this tutorial, we’ll be discussing and implement the Android Menu class in our android application using Kotlin.
We’ll see the different ways in which Menus can be displayed on the screen.

在本教程中,我们将使用Kotlin在我们的android应用程序中讨论和实现Android Menu类。
我们将看到菜单在屏幕上显示的不同方式。

Android菜单 (Android Menu)

Menus are a UI component that is used to display a list of options to perform a quick action.
Menus in Android are largely divided into three different types:

菜单是一个UI组件,用于显示选项列表以执行快速操作。
Android中的菜单大致分为三种类型:

  • Options Menu – These are the most common form of menus. They’re typically displayed in the Toolbar.选项菜单 –这些是最常见的菜单形式。 它们通常显示在工具栏中。
  • Context Menu – These are floating menus that are displayed when a user long clicks on the widget that’s ought to show the Menu上下文菜单 –这些是浮动菜单,当用户长按应显示菜单的小部件时将显示这些菜单
  • Popup Menu – These are displayed on the anchor point above or below the widget that is clicked.弹出菜单 –这些显示在单击的小部件上方或下方的锚点上。

Android Menus can be defined inside the resources folder.
Every menu is associated with an icon and a title along with an attribute: showAsAction.
android:orderInCategory attribute is used to set the order of the menu items in the menu. The highest order occupies the leftmost position. It accepts an integer value.

可以在resources文件夹内定义Android菜单。
每个菜单都与一个图标和一个标题以及一个属性相关联: showAsAction
android:orderInCategory属性用于设置菜单中菜单项的顺序。 最高顺序占据最左侧的位置。 它接受一个整数值。

In the following section, we’ll be creating an Android Application Using Kotlin which will cover each of these menu types.

在下一节中,我们将使用Kotlin创建一个Android应用程序,其中将涵盖每种菜单类型。

项目结构 (Project Structure)

In the res folder create a new resource directory to hold menus.
In the new menu folder that gets created, create a menu resource layout file:

在res文件夹中,创建一个新的资源目录来保存菜单。
在创建的新菜单文件夹中,创建菜单资源布局文件:

码 (Code)

The code for the menu_main.xml menu file is given below:

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"><itemandroid:id="@+id/agenda"android:icon="@android:drawable/ic_menu_agenda"android:orderInCategory="100"android:title="Agenda"app:showAsAction="never" /><itemandroid:id="@+id/call"android:icon="@android:drawable/ic_menu_call"android:orderInCategory="100"android:title="Call"app:showAsAction="always" /><itemandroid:id="@+id/add"android:icon="@android:drawable/ic_menu_add"android:orderInCategory="100"android:title="Add"app:showAsAction="ifRoom" /><itemandroid:id="@+id/compass"android:icon="@android:drawable/ic_menu_compass"android:orderInCategory="100"android:title="Compass"app:showAsAction="always" /><itemandroid:id="@+id/day"android:orderInCategory="100"android:title="Day"app:showAsAction="always|withText" /></menu>

ifRoom value indicates to show the menu icon only if there is space. This priority is the second lowest.
never value indicates that menu icon would not be shown at all in the Toolbar/Menu layout. It’ll reside in the overflow menu.
always indicates that the menu icon.
withText indicates that the menu text would be displayed.

ifRoom值指示仅在有空间时显示菜单图标。 此优先级是第二低的。
never值表示菜单图标在工具栏/菜单布局中根本不会显示。 它将位于溢出菜单中。
始终表示菜单图标。
withText表示将显示菜单文本。

We can club any two of the above values(clubbing never value doesn’t make sense!)

我们可以合并以上两个值中的任何一个(合并永不价值没有意义!)

The code for the popup_menu.xml menu file is given below:

下面给出了popup_menu.xml菜单文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:id="@+id/one"android:title="One" /><itemandroid:id="@+id/two"android:title="Two" /><itemandroid:id="@+id/three"android:title="Three" /></menu>

Menu Items can be grouped too. We can add a checkable behavior on the groups:
popup_menu_group.xml

菜单项也可以分组。 我们可以在组上添加可检查的行为:
popup_menu_group.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"><groupandroid:id="@+id/my_move"android:checkableBehavior="single"><itemandroid:id="@+id/one"android:title="One" /><itemandroid:id="@+id/two"android:title="Two" /><itemandroid:id="@+id/three"android:title="Three" /></group><groupandroid:id="@+id/second"android:checkableBehavior="all"><itemandroid:id="@+id/four"android:checked="true"android:title="Four" /><itemandroid:id="@+id/five"android:title="Five" /><itemandroid:id="@+id/six"android:title="Six" /></group></menu>

The code for the activity_main.xml layout file is given below:

下面给出了activity_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"tools:context=".MainActivity"><Buttonandroid:id="@+id/btnContextMenu"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Context Menu"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintTop_toTopOf="parent" /><Buttonandroid:id="@+id/btnPopUpMenu"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="Popup Menu"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/btnContextMenu" /><Buttonandroid:id="@+id/btnPopUpMenuGroup"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="Popup Menu Group"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/btnPopUpMenu" /></android.support.constraint.ConstraintLayout>

For the Options Menu two methods namely: onCreateOptionsMenu and onOptionsItemSelected need to be overridden. In the onCreateOptionsMenu we inflate the XML menu using the MenuInflater class.

对于选项菜单,需要重写两个方法,即onCreateOptionsMenuonOptionsItemSelected 。 在onCreateOptionsMenu我们使用MenuInflater类为XML菜单充气。

ContextMenu is triggered on a particular view. We need to call registerForContextMenu on that view. This triggers onCreateContextMenu where we add MenuItems in the menu list.
onContextItemSelected is triggered when any ContextMenu is selected.

ContextMenu在特定视图上触发。 我们需要在该视图上调用registerForContextMenu 。 这会触发onCreateContextMenu,我们在菜单列表中添加MenuItems。
当选择任何ContextMenu时会触发onContextItemSelected。

PopupMenu is created when any view is clicked. The PopMenu gets initialized there itself by inflating the menu resource file using the menuInflater. To display the PopupMenu we call the function show on the instance of it.

单击任何视图时将创建PopupMenu。 通过使用menuInflater菜单资源文件,可以自行在其中初始化menuInflater 。 为了显示PopupMenu,我们在其实例上调用show函数。

The code for the MainActivity.kt class is given below:

MainActivity.kt类的代码如下:

package com.journaldev.androidlymenusimport android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.support.v7.widget.PopupMenuclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)registerForContextMenu(btnContextMenu)btnContextMenu.setOnLongClickListener {openContextMenu(btnContextMenu)true}btnPopUpMenu.setOnClickListener {val popup = PopupMenu(this@MainActivity, btnPopUpMenu)//Inflating the Popup using xml filepopup.menuInflater.inflate(R.menu.popup_menu, popup.menu)popup.setOnMenuItemClickListener({if (it.itemId == R.id.one) {Toast.makeText(applicationContext, "One", Toast.LENGTH_SHORT).show()} else {Toast.makeText(applicationContext, "None", Toast.LENGTH_SHORT).show()}true})popup.show()//showing popup menu}btnPopUpMenuGroup.setOnClickListener {val popup = PopupMenu(this@MainActivity, btnPopUpMenu)//Inflating the Popup using xml filepopup.menuInflater.inflate(R.menu.popup_menu_group, popup.menu)popup.setOnMenuItemClickListener({if (it.itemId == R.id.four && it.isChecked) {Toast.makeText(applicationContext, "Four. Was Checked", Toast.LENGTH_SHORT).show()} else {Toast.makeText(applicationContext, it.title, Toast.LENGTH_SHORT).show()}true})popup.show()}}override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {super.onCreateContextMenu(menu, v, menuInfo)menu?.setHeaderTitle("Context Menu")menu?.add(0, v?.id!!, 0, "Call")menu?.add(0, v?.id!!, 1, "SMS")menu?.add(1, v?.id!!, 0, "Search")}override fun onCreateOptionsMenu(menu: Menu): Boolean {val inflater = menuInflaterinflater.inflate(R.menu.menu_main, menu)return true}override fun onContextItemSelected(item: MenuItem?): Boolean {when {item?.title == "Call" -> {Toast.makeText(applicationContext, "Call", Toast.LENGTH_LONG).show()return true}item?.title == "SMS" -> {Toast.makeText(applicationContext, "SMS", Toast.LENGTH_LONG).show()return true}item?.title == "Search" -> {Toast.makeText(applicationContext, "Search", Toast.LENGTH_LONG).show()return true}else -> return super.onContextItemSelected(item)}}override fun onOptionsItemSelected(item: MenuItem): Boolean {when (item.itemId) {R.id.add -> {Log.d("API123", "done")return true}R.id.call -> {Log.d("API123", "done")return true}R.id.day -> {Log.d("API123", "done")return true}R.id.compass -> {Log.d("API123", "done")return true}R.id.agenda -> {Log.d("API123", "done")return true}else -> return super.onOptionsItemSelected(item)}}
}

In the onCreateContextMenu: menu?.add(1, v?.id!!, 0, "Search") is used to add a new menu in the Context Menu.
The first param is the groupId. We can thus have different menu groups within a menu. The second is the menu item id. The third is the priority and the fourth is the title.

onCreateContextMenumenu?.add(1, v?.id!!, 0, "Search")用于在上下文菜单中添加新菜单。
第一个参数是groupId。 因此,我们可以在菜单中拥有不同的菜单组。 第二个是菜单项ID。 第三个是优先级,第四个是标题。

The output of the above application in action is given below:

上面应用程序的输出如下:

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

AndroidlyMenusAndroidlyMenus

翻译自: https://www.journaldev.com/37764/android-menu-using-kotlin

使用Kotlin的Android菜单相关推荐

  1. 用Kotlin开发android平台语音识别语义理解应用

    用Kotlin开发android平台语音识别,语义理解应用(olamisdk) 转载请注明CSDN博文地址:http://blog.csdn.net/ls0609/article/details/75 ...

  2. 用Kotlin开发android平台语音识别,语义理解应用(olamisdk)

    本文使用Kotlin开发Android平台的一个语音识别方面的应用,用的是欧拉密开放平台olamisdk. 1.Kotlin简介 Kotlin是由JetBrains创建的基于JVM的编程语言,Inte ...

  3. 使用Kotlin开发Android应用 - 环境搭建 (1)

    一. 在Android Studio上安装Kotlin插件 按快捷键Command+, -> 在Preferences界面找到Plugins -> 点击Browse repositorie ...

  4. 出现身份验证错误 要求的函数不受支持_学习使用Kotlin创建Android应用程序第3部分:身份验证登录...

    在上一篇文章中,我们讨论了学习Kotlin制作Android应用程序的初学者第2部分:创建登录表单.这次我们来学习创建登录表单后,我们将尝试对上一篇创建的登录表单使用Firebase身份验证.因此,我 ...

  5. 使用Kotlin的Android Spinner

    In this tutorial, we'll be discussing and implementing Spinners in our Android Application using Kot ...

  6. 《Kotlin for android developers》中文版翻译

    <Kotlin for android developers>中文版翻译 错别字.病句.翻译错误等问题可以提issues.请说明错误原因. 在线阅读或下载GitBook 在线阅读 希望大家 ...

  7. 使用Kotlin开发Android应用

    作者:snowdream Email:yanghui1986527#gmail.com QQ 群: 529327615 原文地址:https://snowdream.github.io/blog/20 ...

  8. 用Kotlin写Android Gradle脚本

    Android应用开发中,离不开Gradle脚本的构建.大部分Android开发同学忽视了脚本的力量,甚至有很大一部分同学不知道Gradle脚本是什么,用什么语言编写的:当然,也有相当一部分同学知道G ...

  9. Kotlin for Android

    在Google IO 2017 大会上,Google将 Kotlin列为 Android官方开发语言,Android Studio 3.0 也默认集成了Kotlin插件. Android Studio ...

最新文章

  1. 如何屏蔽ctrl + v 粘贴事件,鼠标右键粘贴事件
  2. MasterPage,Page 2者之间事件的执行顺序
  3. ORACLE 11g 数据库 java jdk版本匹配
  4. 任务管理器taskmgr查看几核
  5. P5091-[模板]欧拉定理
  6. [javaSE] 看博客学习java并发编程
  7. 服务器客户端对话java_java中的服务器和客户机如何使用
  8. (13)ZYNQ AXI总线应用范围(学无止境)
  9. android studio for android learning (二十八) android基础知识
  10. 机械视觉外观检测系统软件ALFA
  11. 关于教程被人盗版出售的一些感想
  12. 177.5. FAQ
  13. 文本分类模型中的“蒸”功夫
  14. Docker(感谢狂神)
  15. 70个居家做饭小技巧
  16. 2018麦考林杂志计算机科学,2018年加拿大大学麦考林杂志排名发布,快来围观你喜欢的学校排名有什么变动没?...
  17. Unity 3d 最新下载与安装
  18. pythonifelse简化_简化“if…elif..else”条件
  19. 教育系统APP(二)
  20. CF1660C Get an Even String(贪心)

热门文章

  1. UVA 10391 STL容器的使用
  2. VMware vSphere Hypervisor下载
  3. [转载] 【Python】Python3 字典 fromkeys()方法
  4. [转载] python中的且语句_简单探讨python中的语句和语法
  5. [转载] Python 多项式拟合(一元回归)
  6. [转载] 抽象类中不能有static,final,private修饰的方法--姥姥家的程序员
  7. 最近纠结致死的一个java报错java.net.SocketException: Connection reset 终于得到解决
  8. redis数据库的基础
  9. HDU4686——Arc of Dream矩阵快速幂
  10. open_cursors参数设置调优