duy anh hoang
duy anh hoang

Reputation: 195

How to implement a switch with text on it in Android Studio 3.0

I want to make a switch with 2 states clearly shown on it like this enter image description here

Instead of this enter image description here

I've tried to write this in the XML file

   android:textOff="1"
   android:textOn="2"

And this on the Java file

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Switch simpleSwitch = findViewById(R.id.simpleSwitch); // initiate Switch
    simpleSwitch.setTextOff("1");
    simpleSwitch.setTextOn("2");
}
}

But the result is always the latter with no text. Can someone guide me through this? It works with toggle buttons but the switch is more suitable for my UI.

Upvotes: 8

Views: 14493

Answers (1)

Uthaya
Uthaya

Reputation: 373

You can enable text inside switch. I think you forgot to add this line

android:showText="true" or Switch.setShowText(boolean)

finally your code be like this,

<Switch
    android:id="@+id/switcher"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:fontFamily="sans-serif-condensed"
    android:textOff="off"
    android:showText="true"
    android:textOn="on" />

Thank you

Upvotes: 15

Related Questions