Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn SwitchCompat on or off in code

Tags:

android

I want to turn a SwitchCompat widget on or off in code. I mean like when user changes a SwitchCompat from On to Off or otherwise. I want to do this in code. How would I do it?

SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);

like image 657
Vahid Amiri Avatar asked Dec 05 '22 01:12

Vahid Amiri


2 Answers

As with any CompoundButton, you change the checked state of a SwitchCompat programmatically via setChecked().

like image 196
CommonsWare Avatar answered Jan 21 '23 10:01

CommonsWare


Programatically to change the state of a SwitchCompat control using setChecked() method.

SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);
switchCompat.setChecked(true); //checked.

or

 switchCompat.setChecked(false); //unchecked.

Or you can define the checked state directly inside the layout:

   <android.support.v7.widget.SwitchCompat
                android:id="@+id/myswitch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"

                android:checked=true/>
like image 41
Jorgesys Avatar answered Jan 21 '23 11:01

Jorgesys