Home » Android » togglebutton – How to make Toggle button programmatically On & OFF in Android?

togglebutton – How to make Toggle button programmatically On & OFF in Android?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to make Toggle button programmatically On & OFF.

How to&Answers:

You can use toggleButton.setChecked(true or false) method to make Toggle button programmatically On & OFF.

Answer:

It’s so simple inside your layout file

<ToggleButton android:id="@+id/ToggleButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Off Stage"
    android:textOn="On Stage"/> 

and in Java

ToggleButton  tglbtn = (ToggleButton)findViewById(R.Id.ToggleButton01);

tglbtn.setChecked(false);

Answer:

Try toggleButton.setSelected(true) & toggleButton.setSelected(false)

It will make toggle on & off.

This will make the toggle to true or false. U can use toggleButton.toggle(); to change from one state to other.

Answer:

Try ToggleButton. It has a .toggle() method to switch the states.

Answer:

in xml file

<ToggleButton android:id="@+id/ToggleButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOff="Off Stage"
    android:textOn="On Stage"/> 

in java file

ToggleButton tglbtn;
    tglbtn=(ToggleButton) findViewById(R.id.ToggleButton01);
    tglbtn.toggle();

this idea also you can try

 tglbtn.setSelected(false);

Answer:

To change both the state and the UI of a toggle button you need to implement two functions:

toggle.setChecked(Boolean value)
toggle.setSelected(Boolean value)

setChecked() sets the intrinsic boolean associated with the view object and setSelected sets the UI.

Answer:

To Toggle set and get value use the following

togg=toggleButton.getText().toString();
    // Get the default value off 
     String off =mo.getOn();
    if (off.equals("OFF")){
    holder.toggleButton.setChecked(false);
    }else{
    holder.toggleButton.setChecked(true);
    }