How to disable scrolling in RecyclerView in Android?

To disable scrolling in RecyclerView, you can achieve this by setting its LayoutManager to a custom LayoutManager and overriding the canScrollHorizontally() and canScrollVertically() methods to return false, thus preventing RecyclerView from scrolling. Here is an example code snippet:

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();
    }
}

Then, in the place where you are using RecyclerView, set the LayoutManager to the custom LayoutManager and call the setScrollEnabled(false) method to disable scrolling.

CustomLayoutManager layoutManager = new CustomLayoutManager(getContext());
layoutManager.setScrollEnabled(false);
recyclerView.setLayoutManager(layoutManager);
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds