How to make Toggle button programmatically On & OFF in Android?
Asked Answered
C

7

13

I need to make Toggle button programmatically On & OFF.

Ceratoid answered 24/6, 2011 at 11:50 Comment(0)
H
27

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

Herbalist answered 24/6, 2011 at 11:55 Comment(0)
D
7

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);
Dockage answered 24/6, 2011 at 12:25 Comment(1)
Worked for Switch too.Calcaneus
M
5

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.

Mick answered 24/6, 2011 at 11:56 Comment(1)
setSelected() doesn't change the toggle state. According to google it does the following: Changes the selection state of this view. A view can be selected or not. Note that selection is not the same as focus. Views are typically selected in the context of an AdapterView like ListView or GridView; the selected view is the view that is highlighted.Seattle
V
2

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

Voluntaryism answered 24/6, 2011 at 11:52 Comment(0)
H
1

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);
Handgrip answered 24/6, 2011 at 11:58 Comment(0)
A
0

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.

Alexipharmic answered 29/6, 2019 at 20:21 Comment(0)
H
0

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);
    }
Highway answered 30/1, 2020 at 4:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.