禁止RecyclerView上下滾動/滑動解決辦法
阿新 • • 發佈:2018-12-11
根據需求,要求RecyclerView不可以滾動,翻閱了不少資料,還是這個最靠譜,自測可行。
1.自定義RecyclerView管理器,我的demo是grid樣式,所以extends GridLayoutManager即可。
public class MyGridLayoutManager extends GridLayoutManager { private boolean isScrollEnabled = true; public MyGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public MyGridLayoutManager(Context context, int spanCount) { super(context, spanCount); } public MyGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) { super(context, spanCount, orientation, reverseLayout); } public void setScrollEnabled(boolean flag) { this.isScrollEnabled = flag; } @Override public boolean canScrollVertically() { return isScrollEnabled && super.canScrollVertically(); } }
注意:若你的RecyclerView所要展示的是列表樣式,那便extends LinearLayoutManager即可,其餘程式碼無變化,程式碼就不貼了。
2.接下來應用自定義的MyGridLayoutManager工具類即可。
@BindView(R.id.rvRoom) RecyclerView rvRoom; MyGridLayoutManager gridLayoutManager = new MyGridLayoutManager(getActivity(),7); gridLayoutManager.setScrollEnabled(false); rvRoom.setLayoutManager(gridLayoutManager);