Android 爲TV端助力之解決ViewPager嵌套RecyclerView水平滑動問題


public class MyViewPager extends ViewPager {
private RecyclerView recyclerView;
public MyViewPager(@NonNull Context context) {
super(context);
}

public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}

public void setView(RecyclerView recyclerView){
this.recyclerView = recyclerView;
}



private int startX, startY;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if(null != recyclerView){
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) ev.getX();
startY = (int) ev.getY();
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
int endX = (int) ev.getX();
//第一種方法
// int endY = (int) ev.getY();
// int disX = Math.abs(endX - startX);
// int disY = Math.abs(endY - startY);
// if(disX > disY){
// getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(startX -endX));
// }else {
// getParent().requestDisallowInterceptTouchEvent(canScrollVertically(startY -endY));
// }

//第二種方法
if(endX>startX){ //表示向左滑動
isVisTop(recyclerView);
}else if(endX<startX){//向右滑動
isVisBottom(recyclerView);
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return super.onInterceptTouchEvent(ev);
}else{
return super.onInterceptTouchEvent(ev);
}
}

public static boolean isVisBottom(RecyclerView recyclerView){
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//屏幕中最後一個可見子項的position
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
//當前屏幕所看到的子項個數
int visibleItemCount = layoutManager.getChildCount();
//當前RecyclerView的全部子項個數
int totalItemCount = layoutManager.getItemCount();
//RecyclerView的滑動狀態
int state = recyclerView.getScrollState();
if(visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 ){
return true;
}else {
return false;
}
}
public static boolean isVisTop(RecyclerView recyclerView){
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//屏幕中最後一個可見子項的position
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
//當前屏幕所看到的子項個數
int visibleItemCount = layoutManager.getChildCount();
//當前RecyclerView的全部子項個數
int totalItemCount = layoutManager.getItemCount();
//RecyclerView的滑動狀態
int state = recyclerView.getScrollState();
if(visibleItemCount > 0 && lastVisibleItemPosition <visibleItemCount){
return true;
}else {
return false;
}
}
}
從新viewPager攔截器onInterceptTouchEvent方法,如上面所示,滑動最左邊或者最右邊的時候就返回true攔截監聽,交給viewPager本身處理,若是不是那就返回false,向下傳遞
相關文章
相關標籤/搜索