Vertically center selected item in RecyclerView

ぐ巨炮叔叔 提交于 2019-12-08 16:01:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39185273/vertically-center-selected-item-in-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!