很多情況的時候我們會用到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