简体   繁体   English

如何在 Kotlin 的 android 工具栏中添加额外的菜单

[英]How to add an extra menu to android toolbar in Kotlin

The question is clear.问题很清楚。 I need to add another menu beside of the main menu in toolbar.我需要在工具栏中的主菜单旁边添加另一个菜单。 I have created the status:xml menu file like this:我创建了这样的状态: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/online"
        android:orderInCategory="10"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/busy"
        android:orderInCategory="20"
        android:title="@string/action_settings"
        app:showAsAction="never" />
    <item
        android:id="@+id/invisible"
        android:orderInCategory="30"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

and added a clickable TextView to toolbar like this:并将可点击的 TextView 添加到工具栏,如下所示:

<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">
            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    ... />
            </androidx.constraintlayout.widget.ConstraintLayout>
        </androidx.appcompat.widget.Toolbar>

Now I need to add it separately to the toolbar, but in code below:现在我需要将它单独添加到工具栏,但在下面的代码中:

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

It add all of items to main menu.它将所有项目添加到主菜单。 Any help will be appreciated.任何帮助将不胜感激。

If this menus have to be separate that appear depending on some kind of condition you can use onPrepareOptionsMenu.如果此菜单必须根据某种条件单独出现,您可以使用 onPrepareOptionsMenu。 Check this question and developer guide on menus Android: Multiple Option Menus in one Activity https://developer.android.com/guide/topics/ui/menus检查此问题和菜单上的开发人员指南Android:一个活动中的多个选项菜单https://developer.android.com/guide/topics/ui/menus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM