Home » Android » android – use RecyclerView like vertical viewpager

android – use RecyclerView like vertical viewpager

Posted by: admin May 14, 2020 Leave a comment

Questions:

is this possible to use recyclerview like verticalpager .
what I want is when a user scrolls always the first item offset from the top be zero. like when you scroll in viewpager. is this possible?

How to&Answers:

Yes, you can.

You can use a simple LinearLayoutManager:

recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL));

and for RecyclerView.Adapter View item use layout_height="match_parent" to get View on full width of screen.

or just use this lib: RecyclerViewPager


Updated:

recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(int newState) {
        if(newState == RecyclerView.SCROLL_STATE_IDLE) {
            // special handler to avoid displaying half elements
            scrollToNext();
        }
        animate();
    }

    @Override
    public void onScrolled(int dx, int dy) {
        animate();
    }
});

Answer:

Since API level 25 there’s a PagerSnapHelper for that:

SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);

See also this answer.