SwitchCompat text not showing up on action bar

329 views Asked by At

I have an action bar on my app and inside the action bar there is a SwitchCompat widget. I've gotten the widget to show up on the action bar but there is no text beside the switch when I test the app.

Here's my menu.xml file

<?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>

Here's my actionview xml file that contains the SwitchCompat widget

<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>

As you can see, I've already added android:text="Night Mode" and android:showText="true" in my action view file. However, the text still doesn't show up. How do I go about this?

Picture of current action bar

1

There are 1 answers

0
mightyandweakcoder On BEST ANSWER

I'm not sure why I could not set the text statically before runtime in the xml file but I solved it dynamically by setting the text of the SwitchCompat in my code.

Here's the Kotlin code:

 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)
    }