SwitchCompat 文本未显示在操作栏上

问题描述

我的应用程序上有一个操作栏,在操作栏中有一个 SwitchCompat 小部件。我已经让小部件显示在操作栏上,但是当我测试应用程序时,开关旁边没有文字

这是我的 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/app_bar_switch"
        android:title="Switch"
        app:showAsAction="always"
        app:actionLayout="@layout/switch_item"
        app:actionViewClass="androidx.appcompat.widget.SwitchCompat" />
</menu>

这是我的 actionview xml 文件,其中包含 SwitchCompat 小部件

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.SwitchCompat
        android:text="Night Mode"
        android:showtext="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

如您所见,我已经在我的操作视图文件添加android:text="Night Mode"android:showtext="true"。但是,文本仍然没有显示。我该怎么办?

Picture of current action bar

解决方法

我不知道为什么我不能在运行前在 xml 文件中静态设置文本,但我通过在我的代码中设置 SwitchCompat 的文本动态解决了它。

这是 Kotlin 代码:

 override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.app_menu,menu);
        val nightMode= menu?.findItem(R.id.app_bar_switch)
        val actionView:SwitchCompat= nightMode?.actionView as SwitchCompat
        actionView.text = "Night Mode"
        return super.onCreateOptionsMenu(menu)
    }