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);
As with any CompoundButton
, you change the checked state of a SwitchCompat
programmatically via setChecked()
.
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/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With