当RecycleView跟ScrollView冲突设置自定义LinearLayoutManager的时候出现IllegalArgumentException异常

很多情况的时候我们会用到RecycleView去代替原始的listView,这样我们就可能会碰到一样的问题,RecycleView与ScrollView滑动冲突,那么我们最佳的解决方案是禁止RecycleView的滑动,让外面的ScrollView整体滑动。那么我们需要重写RecycleView的linearLayoutManager

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.util.AttributeSet;

/**
 * Created by 唐小糖 on 2017/8/11.
 * 重写RecyclerView 的LinearLayoutManager
 * 解决ScrollView中嵌套重写RecyclerView会导致滑动RecyclerView没有惯性效果
 */

public class MyLayoutManager extends LinearLayoutManager {
    private boolean isScrollEnabled = true;

    public MyLayoutManager(Context context) {
        super(context);
    }

    public MyLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public MyLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
    /**
     * 是否支持滑动
     * @param flag
     */
    public void setScrollEnabled(boolean flag) {
        this.isScrollEnabled = flag;
    }

    @Override
    public boolean canScrollVertically() {
        //isScrollEnabled:recyclerview是否支持滑动
        //super.canScrollVertically():是否为竖直方向滚动
        return isScrollEnabled && super.canScrollVertically();
    }
}
然后我们在activity中给RecycleView设置属性即可

            MyLayoutManager myLayoutManager = new MyLayoutManager(this);
            myLayoutManager.setScrollEnabled(false);

            assetsAdapter = new AssetsAdapter(this, list);
            mRecyclerView.setLayoutManager(myLayoutManager);
            mRecyclerView.setAdapter(assetsAdapter);

但是可能某些小伙伴会出现IllegalArgumentException异常,那么是因为你只创建了一个MyLayoutManager却绑定了好几个RecyclerView的原因,MyLayoutManager一个对象只能绑定一个RecyclerView,因此你有多个RecyclerView的时候请实例化对应数量的MyLayoutManager,去绑定RecyclerView

发布了45 篇原创文章 · 获赞 46 · 访问量 14万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章