0

I have a switch in one of my activities and when the user interacts with it in any way a method called onSwitchClick should be executed. Currently, the function executes when the switch is tapped (both from the on and off positions), but never when the switch is "dragged" from one position to the other with a movement of the finger. However, I know the switch's state is being set because another method which turns it off at certain instances does work normally.

Portion of the relevant layout code that formats the activity.

<Switch
    android:id="@+id/switch_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="onSwitchClick"
    android:paddingLeft="5dp"
    android:paddingTop="5dp"
    android:text="@string/switch_text" />
HSM95
  • 21
  • 2
  • *when the user interacts with it in any way a method called onSwitchClick should be executed* one would think that method only gets called when the user *clicks* the switch.. I wonder why ;-) – Tim Apr 07 '15 at 16:40
  • Is using View.OnDragListener an option? You'd have to do it programmatically as opposed to with xml. – Shef Apr 07 '15 at 16:42

1 Answers1

1

Click listeners are only called when views are clicked. To watch for changes in the checked state, like when the switch thumb is dragged to the on or off position, use an OnCheckedChangeListener instead.

Switch switchButton = (Switch) findViewById(R.id.switch_button);
switchButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        ...
    }
});
alanv
  • 23,966
  • 4
  • 93
  • 80