Saturday, August 22, 2015

How to change ToggleButton on/off text in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#ccd4cd"
    >
    <!-- Toggle Button with default on off button text-->
    <ToggleButton
        android:id="@+id/toggle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <!-- Toggle Button with on off button text from XML layout-->
    <ToggleButton
        android:id="@+id/toggle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Click To OFF"
        android:textOff="Click To ON"
        android:layout_below="@id/toggle1"
        />
    <!-- Toggle Button with on off button text programmatically -->
    <ToggleButton
        android:id="@+id/toggle3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/toggle2"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ToggleButton;


public class MainActivity extends Activity {

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

        // Get the widgets reference from XML layout
        ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
        ToggleButton toggle12 = (ToggleButton) findViewById(R.id.toggle2);
        ToggleButton toggle3 = (ToggleButton) findViewById(R.id.toggle3);

        // Set the on button text programmatically for third toggle button
        toggle3.setTextOn("OFF NOW");

        // Set the off button text for third toggle button
        toggle3.setTextOff("ON IT");

        // Initially off the third toggle button
        toggle3.setChecked(false);
  }
}
More android examples