Jai Android
Jai Android

Reputation: 2171

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

I need to make Toggle button programmatically On & OFF.

Upvotes: 13

Views: 44455

Answers (7)

M.Chithirai Perumal
M.Chithirai Perumal

Reputation: 73

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);
    }

Upvotes: 0

Ben
Ben

Reputation: 3804

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.

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

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

Upvotes: 27

Zsombor Erdődy-Nagy
Zsombor Erdődy-Nagy

Reputation: 16914

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

Upvotes: 2

neeraj t
neeraj t

Reputation: 4754

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);

Upvotes: 7

Android
Android

Reputation: 9023

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);

Upvotes: 1

Hussain
Hussain

Reputation: 5562

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.

Upvotes: 5

Related Questions