Reputation: 188
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
?
Upvotes: 3
Views: 21042
Reputation: 1
4 years later found a solution pretty clean and easy for this usecase :
Create your custom switch and override performClick(), that part allows to avoid CompoundButton to react at click :
class CustomSwitch @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : SwitchMaterial(context, attrs, defStyleAttr) {
override fun performClick(): Boolean {
return false
}
}
Second part is to forbid TextView inheritance to react at click and for that just add this to your XML :
android:textIsSelectable="false"
Upvotes: 0
Reputation: 224
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.
Upvotes: 1
Reputation: 322
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());
}
});
Upvotes: 3
Reputation: 962
//onClickListener
public void tglOnClick(View v) {
ToggleButton tgl = (ToggleButton) v;
//do something based on toggle status after clicking
if (tgl.isChecked())
//do something
else
//do something else
//revert button state so that it can be controlled by some external logic
tgl.setChecked(!tgl.isChecked());
}
This worked for me. In my case, the clicking the toggle button sent a request to a service, and if the service replied "OK", the message handler set the correct state of the toggle button.
Upvotes: 0