SnapHelper Item Position

后端 未结 3 829
半阙折子戏
半阙折子戏 2020-12-24 08:37


I\'m using vertical RecyclerView to list my items and SnapHelper to snap center item. The idea is to randomize selection, so user swipe screen

相关标签:
3条回答
  • 2020-12-24 09:28
    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    ....
                }
            })
    
    0 讨论(0)
  • 2020-12-24 09:30

    I used this on a project that had a RecyclerView with SnapHelper, not sure if it is what you want.

    mRecyclerView.setHasFixedSize(true);
    
        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
    
        // specify an adapter (see also next example)
        mAdapter = new DemoSlidesAdapter(getApplicationContext());
        mRecyclerView.setAdapter(mAdapter);
    
        final SnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(mRecyclerView);
    
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE) {
                    View centerView = snapHelper.findSnapView(mLayoutManager);
                    int pos = mLayoutManager.getPosition(centerView);
                    Log.e("Snapped Item Position:",""+pos);
                }
            }
        });
    
    0 讨论(0)
  • 2020-12-24 09:31

    I try to use this code with a PagerSnapHelper to mimic the pager behaviour and it was useful but i found some corner cases to solve, if you move fast from the last page to the first one and keep swapping until see the boundarie then the IDLE state doesnt happen and you lose your index. to solve that I move out the position from the IF and add a extra condition for this corner case.

     override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                 super.onScrollStateChanged(recyclerView, newState)
                 val centerView = snapHelper.findSnapView(mLayoutManager)
                 val pos = mLayoutManager.getPosition(centerView!!)
                 if (newState == RecyclerView.SCROLL_STATE_IDLE || (pos == 0 && newState == RecyclerView.SCROLL_STATE_DRAGGING)) {
                     Log.d("BINDING", "positionView SCROLL_STATE_IDLE: $pos")
                 }
             }
    

    Code is in kotlin hope it helps

    0 讨论(0)
提交回复
热议问题