Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

android - How to scroll recyclerView programmatically?

I have a horizontal recyclerView, When I first open the activity I want to make all the items in recyclerview scroll to the bottom (to the right in this case) and back to the top (to the left). Kinda like an animation. Scroll behavior should be visible to the user.

I tried to do it like:

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);

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>

anim slide right:

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

it works however it just slides the recyclerview as a whole, I just want to scroll(slide) the items. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use scrollToPosition()

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

or smoothScrollToPosition()

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

To move up again, you need to call the above method with index 0. But first, you need to make sure that the RecyclerView is scrolled to last. So, put a ScrollListener on RecyclerView to make sure the last item is visible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...