Java 在Android菜单图标的开关按钮下方/上方添加文本

Java 在Android菜单图标的开关按钮下方/上方添加文本,java,android,android-layout,android-actionbar,android-toolbar,Java,Android,Android Layout,Android Actionbar,Android Toolbar,我试图在我的工具栏中的开关项下/上方添加一个文本,以指示开关的功能。我想知道是否有一个布局标签可以用来在按钮的下方/上方添加文本。或者我必须使用其他方法 menu_main.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:t

我试图在我的
工具栏中的
开关
项下/上方添加一个文本,以指示开关的功能。我想知道是否有一个布局标签可以用来在按钮的下方/上方添加文本。或者我必须使用其他方法

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=".MainActivity">

    <item
        android:id="@+id/edit"
        android:title="@string/app_name"
        app:actionViewClass="android.widget.Switch"
        android:icon="@drawable/ic_edit"
        app:showAsAction="always" android:visible="true"/>

现在看起来是这样的:

这是不必要的。 用户可以理解。 开发人员通常不会将文本放入工具中,而是放置图标。
有关菜单的详细信息,请访问:

您可以创建一个自定义菜单布局,其中包含一个
开关和一个
文本视图

布局/菜单\u layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/menuRoot"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="8dp"
    android:gravity="center"
    android:orientation="vertical">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/menu_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/switch_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="OFF"
        android:textColor="@color/white"
        android:textSize="12sp" />

</LinearLayout>
<?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/switchItem"
        android:title="switch"
        app:actionLayout="@layout/menu_layout"
        app:showAsAction="always" />

</menu>
您可以检测开关单击回调,并相应地更改描述,如下所示:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);

        MenuItem item = menu.findItem(R.id.switchItem);
        LinearLayout root = item.getActionView().findViewById(R.id.menuRoot);
        SwitchCompat menuSwitch = root.findViewById(R.id.menu_switch);
        TextView switchText = root.findViewById(R.id.switch_text);
        menuSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                switchText.setText(isChecked? "ON" : "OFF");
            }
        });
        return true;
    }
预演


我计划再添加几个开关,这样在我看来,有文字会很有帮助