Android滑動與點擊衝突解決辦法

來源:互聯網
上載者:User


緣由

RecyclerView item可以實現滑動的監聽,可以允許使用者左滑動右滑動消失,也允許使用者點擊item。 分別需要重載onTouch與onClick方法,但兩者時間會衝突,onClick會消費掉事件,導致事件不會傳遞到onTouch中。解決方案是將onClick的邏輯移動到onTouch中。

判定條件

參考資料1,使用了時間與移動距離兩個變數要確保使用者的確是想要點擊item。滿足這個條件將會調用onClick裡的邏輯,否則滑動邏輯將被調用。時間控制在1s內, 思路是在ACTION_DOWN中記一個按下按鈕的時間,在ACTION_UP判斷是否ACTION_UP到ACTION_DOWN需要的時間小不小於1s;距離是衡量值是從ViewConfiguration這個類中取出來的,是安卓推薦的資料。

具體代碼

private static final int MAX_CLICK_DURATION = 1000;

private int mSlop;

private long pressStartTime;
private float pressedX;
private float pressedY;

...

ViewConfiguration vc = ViewConfiguration.get(builder.mRecyclerView.getContext());
mSlop = vc.getScaledTouchSlop();

...

case MotionEvent.ACTION_DOWN: {
    pressStartTime = System.currentTimeMillis();
    pressedX = motionEvent.getX();
    pressedY = motionEvent.getY();

...

case MotionEvent.ACTION_UP: {
    long pressDuration = System.currentTimeMillis() - pressStartTime;
        if (pressDuration < MAX_CLICK_DURATION && distance(pressedX, pressedY,                  motionEvent.getX(), motionEvent.getY()) < mSlop) {
                mItemClickCallback.onClick(mRecyclerView.getChildPosition(mDownView));
                 return true;
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.