Change Toggle Button text in android programmatically

 How to create toggle button with custom above text define by setTextOn() and setTextOff() methods.

In this tutorial we are using two methods setTextOff() and setTextOn() to dynamically set up the toggle button above text from MainActivity.java programming file. So here is the complete step by step tutorial for Change Toggle Button text in android programmatically.

android-project-download-code-button

How to Change Toggle Button text in android programmatically.

Code for MainActivity.java file.

 package com.changetogglebuttontextprogrammatically_android_examples.com;

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

public class MainActivity extends Activity {

 ToggleButton togglebutton;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 togglebutton = (ToggleButton)findViewById(R.id.toggleButton1);
 
 togglebutton.setTextOn("Toggle Button On Text Dynamically");
 
 togglebutton.setTextOff("Toggle Button Off Text Dynamically");
 
 
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.changetogglebuttontextprogrammatically_android_examples.com.MainActivity" >

 <ToggleButton
 android:id="@+id/toggleButton1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 />

</RelativeLayout>

Screenshots:

Change Toggle Button text in android programmatically

 

toggle-button-text-2

Click here to download Change Toggle Button text in android programmatically project with source code.