动画水平滚动视图在android工作室



我正在尝试设置水平滚动视图的动画。目前,它从左到右完美地与:

HorizontalScrollView headband = findViewById(R.id.scroll);
ObjectAnimator.ofInt(headband, "scrollX", 2000).setDuration(10000).start();

现在我想要两样东西:

  • 如何从右到左进行逆运算?我认为睡眠不是一个好的选择
  • 何想知道我的滚动视图的像素大小?由于我使用的2000值是随机的,只是起作用

经过数周的斗争,这里是解决方案!希望它对某人有用。

HorizontalScrollView headband = findViewById(R.id.scroll);

animator1 = ObjectAnimator.ofInt(headband, "scrollX",  1700).setDuration(10000);
animator2 = ObjectAnimator.ofInt(headband, "scrollX",  0).setDuration(10000);
animator1.start();
animator1.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
animator2.start();
}
});
animator2.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
animator1.start();
}
});

您可以使用ObjectAnimatorrepeatMode使其在相反的方向上重复,使用repeatCount使其无限期地继续。您可以通过计算scrollView[0].width - scrollView.width来获得ScrollView的可滚动大小。以下是在Kotlin中使用变量的情况:

ObjectAnimator.ofInt(headband, "scrollX", 0, headband[0].width - headband.width).apply {
repeatMode = ObjectAnimator.REVERSE
repeatCount = Animation.INFINITE
duration = 10000
start()
}

如果您在视图宽度未知的地方执行此操作,例如在onCreate()中,则它们会将其全部封装在headband.doOnLayout { <code> }中。

最新更新