某些应用场景,TextView需要长按复制,即textIsSelectable=true,系统会给我们实现该功能,然而我们又给TextView设置了OnClickListener的事件,这时候我们点击TextView,第一次会没有反应,OnClickListener的onClick并不执行,再点击第二次才会执行。
我们可以自行处理onTouchEvent事件来实现该效果:
public class CustomTextView extends AppCompatTextView {
public CustomTextView(Context context) {
super(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private long mLastActionDownTime = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
long actionUpTime = System.currentTimeMillis();
if (actionUpTime - mLastActionDownTime <= ViewConfiguration.getLongPressTimeout()) {
performClick();
return true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
mLastActionDownTime = System.currentTimeMillis();
}
return super.onTouchEvent(event);
}
}
另:如何解决TextView的ClickableSpan、OnClickListener、OnLongClickListener冲突的问题,请阅读博文。