如何以编程方式滚动recyclerView? [英] How to scroll recyclerView programmatically?
问题描述
我有一个水平的recyclerView,当我第一次打开活动时,我想使recyclerview中的所有项目滚动到底部(在这种情况下为右侧),再滚动到顶部(左侧).有点像动画.滚动行为应该对用户可见.
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.
我试图这样做:
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);
动画向左滑动:
<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>
向右滑动动画:
<translate
android:duration="200"
android:fromXDelta="100%"
android:fromYDelta="0%"
android:toXDelta="0%"
android:toYDelta="0%" />
它可以工作,但是它只是将recyclerview整体滑动,我只想滚动(滑动)项目.我该怎么办?
it works however it just slides the recyclerview as a whole, I just want to scroll(slide) the items. How can I do this?
推荐答案
您可以使用scrollTo()
recyclerView.post(new Runnable() {
@Override
public void run() {
recyclerView.scrollToPosition(adapter.getItemCount() - 1);
// Here adapter.getItemCount()== child count
}
});
或smoothScrollToPosition()
recyclerView.post(new Runnable() {
@Override
public void run() {
recyclerView.smoothScrollToPosition(adapter.getItemCount()- 1);
}
});
要再次上移,您需要使用索引0调用上述方法.但是首先,需要确保RecyclerView
滚动到最后.
因此,在RecyclerView
上放置ScrollListener
以确保最后一个项目可见.
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.
这篇关于如何以编程方式滚动recyclerView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!