Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android How do I correctly get the value from a Switch?

I'm creating a Android application which uses a Switch.
I'm trying to listen for changes and get the value when changed.
I have two questions when using switches:

  1. What action listener do I use?
  2. How do I get the the switch value?
like image 968
stackoverflow Avatar asked May 14 '12 00:05

stackoverflow


People also ask

How do you find the value of switch?

To access the value of the switch, you need to do the following: ((Switch) findViewById(R. id. switch_id)).

What is a switch button in Android Studio?

A toggle button allows the user to change a setting between two states. You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.

How do I know if my Android switch is enabled?

ImageButton myButton = (ImageButton) findViewById(R. id. epic_button); if (myButton. isEnabled()){ //then the button is enabled. }


1 Answers

Switch s = (Switch) findViewById(R.id.SwitchID);  if (s != null) {     s.setOnCheckedChangeListener(this); }  /* ... */  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {     Toast.makeText(this, "The Switch is " + (isChecked ? "on" : "off"),                    Toast.LENGTH_SHORT).show();     if(isChecked) {         //do stuff when Switch is ON     } else {         //do stuff when Switch if OFF     } } 

Hint: isChecked is the new switch value [true or false] not the old one.

like image 189
Kazekage Gaara Avatar answered Oct 06 '22 00:10

Kazekage Gaara