Sometimes, we use ordinary TextView instead of Button, sometimes it's not a list (personal habit, the Button with map on the homepage doesn't like to be a list, prefer to be intuitive). At this time, we need to press the background color change effect, and we need to use selector to achieve it. At this time, there is a problem that no matter whether it is in the control or not, the action "up" is triggered instead of the action "Cancel" on the Xiaomi 5x, so the following methods are adopted to solve the problem:
btnNext.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_CANCEL:
btnNext.setSelected(false);
break;
case MotionEvent.ACTION_DOWN:
btnNext.setSelected(true);
break;
case MotionEvent.ACTION_UP:
//Determine if it is moving to the outside and then raising the finger
if(isOutterUp(event,v)){
event.setAction(MotionEvent.ACTION_CANCEL);
return onTouch(v,event);
}
btnNext.setSelected(false);
click(v);
break;
}
return true;
}
private boolean isOutterUp(MotionEvent event, View v) {
float touchX = event.getX();
float touchY = event.getY();
float maxX = v.getWidth();
float maxY = v.getHeight();
return touchX<0 || touchX>maxX || touchY < 0 || touchY > maxY;
}
private void click(View v) {
//Click
}
});
In short, the action up that is moved to the outside of the control and lifted is treated as action cancel. The following figure shows all cases beyond the boundary.
Of course, the same listener can be integrated for processing. The modified code is as follows:
Parent class:
private OnTouchListener mSelectListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_CANCEL:
v.setSelected(false);
break;
case MotionEvent.ACTION_DOWN:
v.setSelected(true);
break;
case MotionEvent.ACTION_UP:
if(isOutterUp(event,v)){
event.setAction(MotionEvent.ACTION_CANCEL);
return onTouch(v,event);
}
v.setSelected(false);
v.performClick();
break;
}
return true;
}
private boolean isOutterUp(MotionEvent event, View v) {
float touchX = event.getX();
float touchY = event.getY();
float maxX = v.getWidth();
float maxY = v.getHeight();
return touchX<0 || touchX>maxX || touchY < 0 || touchY > maxY;
}
};
protected void setOnSelectListener(View v,OnClickListener mOnClickListener){
v.setOnClickListener(mOnClickListener);
v.setOnTouchListener(mSelectListener);
}
Subclass use:
setOnSelectListener(drawTxtAttend, new OnClickListener() {
@Override
public void onClick(View v) {
//Click event handling
}
});