recyclerview添加scrollListener

时间:2019-04-03 12:40:57

标签: android android-recyclerview

我有一个RecyclerView和一个水平LinearLayoutManager。 我想检查ScrollListener。 我的目标是检查以下步骤:

  1. 检查何时RecyclerView开始滚动
  2. 检查何时RecyclerView结束滚动
  3. 检查RecyclerView的滚动条是否居中

这是我的RecyclerView代码,LinearLayoutManager

LinearLayoutManager horizontalManager = new LinearLayoutManager(context);
        horizontalManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewHolderStory.recyclerView.setLayoutManager(horizontalManager);
        viewHolderStory.recyclerView.addItemDecoration(new PaddingItemDecoration((Activity) context));
        viewHolderStory.recyclerView.setHasFixedSize(true);
        viewHolderStory.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

            }
        });
        viewHolderStory.recyclerView.setNestedScrollingEnabled(false);

是否可以在我的addOnScrollListener方法上添加验证?

2 个答案:

答案 0 :(得分:0)

 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE){
                    /// User Stops Scroll
                 }
                if(newState==RecyclerView.SCROLL_STATE_DRAGGING){
                 /// User Starts Scroll
              }
            }

您可以从this中找到更多信息。

答案 1 :(得分:0)

您可以使用computeVerticalScrollExtent()computeVerticalScrollOffset()computeVerticalScrollRange()

进行计算

如果您的Recyler视图是水平的,则这些功能具有水平的对应功能

完整代码:

viewHolderStory.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
{
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        int extent = recyclerView.computeVerticalScrollExtent();
        int offset = recyclerView.computeVerticalScrollOffset();
        int range = recyclerView.computeVerticalScrollRange();

        if(offset == 0){
            //fire when recycler view hit top
            Log.i("myTag", "onScrolled: top");
        }
        else if(offset + extent == range){
            //fire when recycler view hit bottom
            Log.i("myTag", "onScrolled: bottom");
        }
        else {
            //fire the rest of the time
            Log.i("myTag", "onScrolled: middle");
        }
    }
});