项目中时常须要实如今ScrollView中嵌入一个或多个RecyclerView。这一作法一般会致使以下几个问题html
本文将利用多种方式分别解决上述问题java
若只存在滑动卡顿这一问题,能够采用以下两种简单方式快速解决ide
recyclerView.setHasFixedSize(true); recyclerView.setNestedScrollingEnabled(false);
其中,setHasFixedSize(true)方法使得RecyclerView可以固定自身size不受adapter变化的影响;而setNestedScrollingeEnabled(false)方法则是进一步调用了RecyclerView内部NestedScrollingChildHelper对象的setNestedScrollingeEnabled(false)方法,以下布局
public void setNestedScrollingEnabled(boolean enabled) { getScrollingChildHelper().setNestedScrollingEnabled(enabled); }
进而,NestedScrollingChildHelper对象经过该方法关闭RecyclerView的嵌套滑动特性,以下this
public void setNestedScrollingEnabled(boolean enabled) { if (mIsNestedScrollingEnabled) { ViewCompat.stopNestedScroll(mView); } mIsNestedScrollingEnabled = enabled; }
如此一来,限制了RecyclerView自身的滑动,整个页面滑动仅依靠ScrollView实现,便可解决滑动卡顿的问题spa
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) { @Override public boolean canScrollVertically() { return false; } };
这一方式使得RecyclerView的垂直滑动始终返回false,其目的一样是为了限制自身的滑动code
如果须要综合解决上述三个问题,则能够采用以下几种方式htm
在原有布局中插入一层LinearLayout/RelativeLayout,造成以下布局对象
该方法的核心思想在于经过重写LayoutManager中的onMeasure()方法,即blog
@Override public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) { super.onMeasure(recycler, state, widthSpec, heightSpec); }
从新实现RecyclerView高度的计算,使得其可以在ScrollView中表现出正确的高度,具体重写方式可参考这篇文章
http://www.cnblogs.com/tianzh...
该方法的核心思想在于经过重写ScrollView的onInterceptTouchEvent(MotionEvent ev)方法,拦截滑动事件,使得滑动事件可以直接传递给RecyclerView,具体重写方式可参考以下
/** * Created by YH on 2017/10/10. */ public class RecyclerScrollView extends ScrollView { private int slop; private int touch; public RecyclerScrollView(Context context) { super(context); setSlop(context); } public RecyclerScrollView(Context context, AttributeSet attrs) { super(context, attrs); setSlop(context); } public RecyclerScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setSlop(context); } /** * 是否intercept当前的触摸事件 * @param ev 触摸事件 * @return true:调用onMotionEvent()方法,并完成滑动操做 */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: // 保存当前touch的纵坐标值 touch = (int) ev.getRawY(); break; case MotionEvent.ACTION_MOVE: // 滑动距离大于slop值时,返回true if (Math.abs((int) ev.getRawY() - touch) > slop) return true; break; } return super.onInterceptTouchEvent(ev); } /** * 获取相应context的touch slop值(即在用户滑动以前,可以滑动的以像素为单位的距离) * @param context ScrollView对应的context */ private void setSlop(Context context) { slop = ViewConfiguration.get(context).getScaledTouchSlop(); } }
事实上,尽管咱们可以采用多种方式解决ScrollView嵌套RecyclerView所产生的一系列问题,但因为上述解决方式均会使得RecyclerView在页面加载过程当中一次性显示全部内容,所以当RecyclerView下的条目过多时,将会对影响整个应用的运行效率。基于此,在这种状况下咱们应当尽可能避免采用ScrollView嵌套RecyclerView的布局方式