0

I have in my app an an settings activity with many switches. I tried to avoid writing 50 setOnCheckedChangeListener I tried to set a onClick event in the layout file:

        <Switch
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/switchVibra"
            android:layout_weight="0.1"
            android:onClick="switchChange" />

The methode:

public void switchChange(View v){
    switch (v.getId()){
        case R.id.switchVibra:
           // Do something
           break;
   }
}

But this method doesn't register a change when you wipe the switch. Is there a other option to avoid writing a listener for every switch?

Laire
  • 1,290
  • 6
  • 22
  • 49
  • what do you mean with 'doesn't register a change'? Have you verified that it's being called by adding Log statements? – Sebastian Aug 07 '15 at 11:55
  • [http://stackoverflow.com/questions/7187287/how-to-know-whether-user-has-changed-the-state-of-toggle-button](http://stackoverflow.com/questions/7187287/how-to-know-whether-user-has-changed-the-state-of-toggle-button) – M D Aug 07 '15 at 11:55
  • @Sebastian: Yes i have verified it. – Laire Aug 07 '15 at 12:18

2 Answers2

10

Switch does not use a click listener, it uses OnCheckedChangeListener which cant be set from XML.

Do the following

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    CompoundButton.OnCheckedChangeListener multiListener = new CompoundButton.OnCheckedChangeListener() {

        public void onCheckedChanged(CompoundButton v, boolean isChecked) {
            switch (v.getId()){
                case R.id.switchVibra:
                    // Do something
                    break;
            }
       }
    });

    //on each switch
    ((Switch) findViewById(R.id.switchVibra)).setOnCheckedChangeListener(multiListener);
}
Nick Cardoso
  • 20,807
  • 14
  • 73
  • 124
0

You can also try like this.. Suppose switch name like switch1, switch2, switch2..... switch10

public class MainActivity extends Activity implements OnCheckedChangeListener{

int nSwitch=10;
Switch[] switchs = new Switch[nSwitch];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    for(int i=1;i<=nSwitch;i++){
        String mySwitch = "switch"+i;
        int switchId = getResources().getIdentifier(mySwitch, "id", "com.example.SwitchDemo");

        switchs[i-1] = ((Switch)findViewById(switchId));
        switchs[i-1].setOnCheckedChangeListener(this);


    }
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub

    //here you can do anythig for your particular Switch onCheckedChanged.. 

}

}

Where "com.example.SwitchDemo" full package name.