android中recyclerview禁止滑動(dòng)怎么實(shí)現(xiàn)

小億
868
2024-03-08 10:05:24

要禁止RecyclerView的滑動(dòng),可以通過(guò)設(shè)置其LayoutManager為一個(gè)自定義的LayoutManager,并在該自定義LayoutManager中重寫canScrollHorizontally()和canScrollVertically()方法,使其返回false,從而禁止RecyclerView的滑動(dòng)。以下是一個(gè)示例代碼:

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

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

    public void setScrollEnabled(boolean flag) {
        this.isScrollEnabled = flag;
    }

    @Override
    public boolean canScrollHorizontally() {
        return isScrollEnabled && super.canScrollHorizontally();
    }

    @Override
    public boolean canScrollVertically() {
        return isScrollEnabled && super.canScrollVertically();
    }
}

然后在使用RecyclerView的地方,將LayoutManager設(shè)置為該自定義LayoutManager,并調(diào)用setScrollEnabled(false)方法來(lái)禁止滑動(dòng):

CustomLayoutManager layoutManager = new CustomLayoutManager(getContext());
layoutManager.setScrollEnabled(false);
recyclerView.setLayoutManager(layoutManager);

0