1. 程式人生 > >解決ScrollView巢狀RecyclerView(橫向)或ListView(橫向)時,橫向滑動不順暢的問題。

解決ScrollView巢狀RecyclerView(橫向)或ListView(橫向)時,橫向滑動不順暢的問題。

程式碼簡單,容易理解,裡面有點註釋,夠看了,特別少的改動。

package com.laka.live.ui.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;


/**
 * Created by Lyf on 2017/8/3.
 * 解決ScrollView與RecyclerView橫向滾動時的事件衝突
 */
public class ScrollRecyclerView extends RecyclerView { public ScrollRecyclerView(Context context) { super(context); } public ScrollRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ScrollRecyclerView(Context context, @Nullable AttributeSet attrs, int
defStyle) { super(context, attrs, defStyle); } private float lastX, lastY; @Override public boolean onInterceptTouchEvent(MotionEvent e) { boolean intercept = super.onInterceptTouchEvent(e); switch (e.getAction()) { case MotionEvent.ACTION_DOWN: lastX = e.getX(); lastY = e.getY(); break
; case MotionEvent.ACTION_MOVE: // 只要橫向大於豎向,就攔截掉事件。 // 部分機型點選事件(slopx==slopy==0),會觸發MOVE事件。 // 所以要加判斷(slopX > 0 || sloy > 0) float slopX = Math.abs(e.getX() - lastX); float slopY = Math.abs(e.getY() - lastY); // Log.log("slopX=" + slopX + ", slopY=" + slopY); if((slopX > 0 || sloy > 0) && slopX >= slopY){ requestDisallowInterceptTouchEvent(true); intercept = true; } break; case MotionEvent.ACTION_UP: intercept = false; break; } // Log.log("intercept"+e.getAction()+"=" + intercept); return intercept; } }

備註:如果是ListView,直接將上面的RecyclerView類換成ListView就行了。