滚动停止上的回收者视图

Gil*_*oza 0 android android-recyclerview

基本上我希望我的 recyclerview 自动滚动到项目未显示一半的位置。就像 googleplay 中的那个。

我写了一个代码

public void scrollToVisible(){
    int firstVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
    View view = recyclerView.getLayoutManager().getChildAt(0);
    if (firstVisibleItemPosition > 0 && view != null) {
        int offsetTop = view.getTop();
        if (firstVisibleItemPosition - 1 >= 0 && adapter.getItemCount() > 0) {
            ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(firstVisibleItemPosition - 1, offsetTop);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题来了。我不知道把这段代码放在哪里。当 recyclerview 停止滚动时,我有一个模糊的想法,但我已经搜索了很长一段时间,但找不到这样的方法。当我把它放在 onScroll 上时会出现一些意想不到的行为

小智 5

您可以创建一个扩展RecyclerViewCustomRecyclerView

public class CustomRecyclerView extends RecyclerView {
@Override
public void onScrollStateChanged(int state) {
    super.onScrollStateChanged(state);

    // check if scrolling has stopped
    if (state == SCROLL_STATE_IDLE) {
         LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager();
         // use code here
    }
}
Run Code Online (Sandbox Code Playgroud)