Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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.

like image 248
duy anh hoang Avatar asked Feb 01 '18 01:02

duy anh hoang


People also ask

What is toggle button How do you create it explain with example?

In Android, ToggleButton is used to display checked and unchecked state of a button. ToggleButton basically an off/on button with a light indicator which indicate the current state of toggle button. The most simple example of ToggleButton is doing on/off in sound, Bluetooth, wifi, hotspot etc.

What is clickable in Android Studio?

Certain View types, like Button , are denoted as clickable by default. In your app, if the View is not clickable, or does not perform an action when clicked, remove its OnClickListener or set android:clickable="false" .

How do you use the switch button on Kotlin?

Android Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF. The Switch element is useful when only two states require for activity either choose ON or OFF.


1 Answers

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

like image 71
Uthaya Avatar answered Oct 19 '22 23:10

Uthaya