如何以编程方式滚动recyclerView?

Ege*_*glu 10 android android-layout android-recyclerview

我有一个水平的recyclerView,当我第一次打开活动时,我想让recyclerview中的所有项目滚动到底部(在这种情况下向右)并返回到顶部(向左).有点像动画.滚动行为应该对用户可见.

我试着这样做:

Animation slideRight = AnimationUtils.loadAnimation(this, R.anim.slide_right);
        Animation slideLeft = AnimationUtils.loadAnimation(this, R.anim.slide_left);
        slideRight.setDuration(1000);
        slideLeft.setDuration(1000);
        slideRight.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                recyclerView.startAnimation(slideLeft);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        recyclerView.startAnimation(slideRight);
Run Code Online (Sandbox Code Playgroud)

anim slide left:

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <translate
        android:duration="200"
        android:fromXDelta="-100%"
        android:fromYDelta="0%"
        android:toXDelta="0%"
        android:toYDelta="0%" />

</set>
Run Code Online (Sandbox Code Playgroud)

向右滑动:

<translate
    android:duration="200"
    android:fromXDelta="100%"
    android:fromYDelta="0%"
    android:toXDelta="0%"
    android:toYDelta="0%" />
Run Code Online (Sandbox Code Playgroud)

它可以工作,但它只是将recyclerview作为一个整体滑动,我只想滚动(滑动)项目.我怎样才能做到这一点?

ADM*_*ADM 17

您可以使用 scrollTo()

  recyclerView.post(new Runnable() {
        @Override
        public void run() {
            recyclerView.scrollToPosition(adapter.getItemCount() - 1);
            // Here adapter.getItemCount()== child count
        }
    });
Run Code Online (Sandbox Code Playgroud)

或者smoothScrollToPosition().

recyclerView.post(new Runnable() {
        @Override
        public void run() {
            recyclerView.smoothScrollToPosition(adapter.getItemCount()- 1);
        }
    });
Run Code Online (Sandbox Code Playgroud)

要再次向上移动,您需要使用索引0调用上面的方法.但首先,您需要确保RecyclerView滚动到最后.因此,把ScrollListenerRecyclerView,以确保最后一个项目是可见的.

  • `recyclerView.postDelayed(() -&gt; recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount() - 1), 1000); recyclerView.postDelayed(() -&gt; recyclerView.smoothScrollToPosition(0),500); ` 是一个选项,但它滚动得很快 (2认同)