这些天的开发中需要用到PullToRefreshScrollView嵌套recyclerview,代码写完之后发现了几个问题:
- 滑动出现了冲突,没有滑动惯性了,
- 在当前页面跳转到其他页面,再回到当前页面的时候recyclerview会自动滑动到顶端,
针对以上问题我也找到了相应的解决方法:
1、解决滑动的冲突:
在网上找的方法是通过事件分发机制,自定义ScrollView解决,
public boolean onInterceptTouchEvent(MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
downX = (int) e.getRawX();
downY = (int) e.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveY = (int) e.getRawY();
if (Math.abs(moveY - downY) > mTouchSlop) {
return true;
}
}
return super.onInterceptTouchEvent(e);
}
因为我使用了第三方PullToRefreshScrollView,如果自定义的话需要继承这个类,But在这个pulltorefreshBase这个类里面已经将此方法写成final,也就是我们没法重写了。
Paste_Image.png
经过一般查找资料后又有了新的发现,
在使用recyclerview的时候会用到LayoutManager,此时我们只需要将LayoutManager里面的滑动给关闭掉,也就是返回false即可,这样就可以解决了冲突引起的失去惯性。
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(),2){
@Override
public boolean canScrollVertically()
{
return false;
}
};
rv_classify_content.setLayoutManager(gridLayoutManager);
2、解决RecyclerView自动滑动到顶端的问题
进入页面自动跳转到recyclerView最顶端,页面会自动滚动貌似是RecyclerView 自动获得了焦点,
这里的解决方法也很简单,就是RecyclerView去焦点。有两种办法:
recyclerview.setFocusableInTouchMode(false);
recyclerview.requestFocus();
或者在布局XML文件中,scrollview里面的第一层LinearLayout添加descendantFocusability属性如下:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
这样写完后两个问题都解决了。
这里补充一下:
descendantFocusability属性是当一个为view获取焦点时,定义viewGroup和其子控件两者之间的关系。
属性的值有三种:
- beforeDescendants:viewgroup会优先其子类控件而获取到焦点
- afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
- blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
总结:以上是我在开发中遇到的问题,记录下来希望对大家有帮助,如果有不同观点和想法的朋友们也可以在评论中指点出来。