TextView設置了長按複製、OnClickListener衝突的問題

某些應用場景,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);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章