Switch button, disable change state onClick
Solution 1
If you want to only change the state of the switch with swipe do the following:
switchbutton = view.findViewById(R.id.switch2);
switchbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchbutton.setChecked(!switchbutton.isChecked());
}
});
Solution 2
Using a switch widget you will have to create your customSwitch class and override the onTouchEvent method to return true when you detect a click:
public boolean onTouchEvent(MotionEvent ev) {
boolean response;
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
x = ev.getX();
response = super.onTouchEvent(ev);
break;
case MotionEvent.ACTION_UP:
response = Math.abs(x - ev.getX()) <= 10 || super.onTouchEvent(ev);
break;
default:
response = super.onTouchEvent(ev);
break;
}
return response;
}
The number 10 is a tolerance value as some devices report a movement event of 3 or 6 pixels or so instead of a click, so with this you control: 10 pixels or less is click (and ignore it) or more distance is considered movement and let this movement pass trought normal switch behaivor.
Declare x as a class level variable, default value is 0. MotionEvent.ACTION_DOWN is allways called first so you will have x with the starting value on the X axis of the MotionEvent.
bott
Updated on June 04, 2022Comments
-
bott about 2 years
I want to use a switch button but I want to disable the change status on click, let this change only to the drag option. I try to set
onclick
listener to do nothing but when I click on the button always change the state.Some one know to disable the change status
onClick
? -
bott over 10 yearsIm using switch button not a button. I want to disable the change state function on click and only let this function in the drag event
-
Kaushik over 10 yearsu can use that for switch button also
-
bott over 10 yearsYeah but the problem is the same, when you click the button that button change her state (on->off, off->on) and later enter in that function (onToggleClicked in that case). I want to prevent/eliminated the change state on click
-
Akash Raghav almost 6 yearsx is not initialised in the method. where to initialise x and what to put as its default value?