采用結(jié)構(gòu)
PtrFrameLayout 嵌套一個(gè)帶下拉刷新的RecyclerView
PtrFrameLayout是一個(gè)自定義下拉刷新布局RV內(nèi)部Item包含一個(gè)橫向滑動(dòng)的RecyclerView在頂部
導(dǎo)致的問題:橫向滑動(dòng)RecyclerView時(shí)經(jīng)常容易引起下拉刷新,這種體驗(yàn)很差
解決思路
繼承RecyclerView,重寫dispatchTouchEvent盏檐,根據(jù)ACTION_MOVE的方向判斷是否調(diào)用getParent().requestDisallowInterceptTouchEvent去阻止父view攔截點(diǎn)擊事件
通過繼承PtrFrameLayout翻默,重寫requestDisallowInterceptTouchEvent方法腰根,獲取disallowIntercept來判斷是否分發(fā)事件給父View(避免父View獲取事件引起下拉操作)
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
disallowInterceptTouchEvent = disallowIntercept;
//子View告訴父容器不要攔截我們的事件的
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}```
#### 具體源碼
* 重寫橫向滑動(dòng)RecyclerView
public class BetterRecyclerView extends RecyclerView {
private ViewGroup parent;
public BetterRecyclerView(Context context) {
super(context);
}
public BetterRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setNestParent(ViewGroup parent) {
this.parent = parent;
}
private int lastX = -1;
private int lastY = -1;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getRawX();
int y = (int) ev.getRawY();
int dealtX = 0;
int dealtY = 0;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
dealtX = 0;
dealtY = 0;
// 保證子View能夠接收到Action_move事件
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
dealtX += Math.abs(x - lastX);
dealtY += Math.abs(y - lastY);
// Log.i("dispatchTouchEvent", "dealtX:=" + dealtX);
// Log.i("dispatchTouchEvent", "dealtY:=" + dealtY);
// 這里是夠攔截的判斷依據(jù)是左右滑動(dòng)新翎,讀者可根據(jù)自己的邏輯進(jìn)行是否攔截
if (dealtX >= dealtY) {
getParent().requestDisallowInterceptTouchEvent(true);
} else {
getParent().requestDisallowInterceptTouchEvent(false);
}
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
break;
}
return super.dispatchTouchEvent(ev);
}
* 重寫PtrFrameLayout的部分源碼
private boolean disallowInterceptTouchEvent = false;
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
disallowInterceptTouchEvent = disallowIntercept;
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_UP:
this.requestDisallowInterceptTouchEvent(false);
disableWhenHorizontalMove(true);
break;
}
if (disallowInterceptTouchEvent) {
return dispatchTouchEventSupper(e);
}
return super.dispatchTouchEvent(e);
}