Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center selected item in RecyclerView

I'm trying to implement some kind of wheel picker for my app, because the current options rely on custom Views or the old ListView, so I'd like to base my solution on RecyclerView.

What I did until now was to set at the beginning and at the end of the RecyclerView two View with a different type, named PADDING_TYPE so that the first and the last item are vertically centered in the RecyclerView.

recyclerView.post(new Runnable() {
    @Override
    public void run() {
        //80dp is the height of a regular list item
        int paddingHeight = ((recyclerView.getHeight()-SettingsManager.dptopixels(80))/2);
        binding.getRoot().getLayoutParams().height = paddingHeight;
    }
});

Now I'm trying to understand how to keep the selected item vertically centered.

What I tried so far:

1- LinearSnapHelper

LinearSnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(mRecyclerView);

Does not work as expected, I also tried to Override several methods (probably in a wrong way), but I can't make it automatically vertically center the selection. And it's not snappy enough, the selected item "moves" instead of being locked to vertical center.

2- Custom RecyclerView.OnScrollListener

I tried to adapt the code proposed here, which is for horizontal scrolling, by changing in the RecyclerView.OnScrollListener this line

allPixelsDate += dx;

with the vertical scrolling difference:

allPixelsDate += dy;

This implementation is close to be working, because it selects the closest item to the vertical center of the list, but without locking it to the center.

Would it be possible to achieve such result? How?

To be more clear: I'd like to achieve the result shown here at 1:10. The selection is "locked" at center.

like image 836
Vektor88 Avatar asked Aug 27 '16 20:08

Vektor88


1 Answers

You just need to use LinearSnapHelper and the setOnFlingListener(snapHelper) method on your RecyclerView.

This is working example:

LinearSnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setOnFlingListener(snapHelper);

To get real wheel picker you will also need to add some skin for your wheel and to accurately calculate height of rows and height of the RecyclerView. For example if you want to display only 3 rows in your wheel you need RecyclerView height to be 3 times larger than row height.

like image 140
lobzik Avatar answered Sep 28 '22 12:09

lobzik