可以试试这个。这是使用 TranslateAnimation 创建自动滚动文本(水平滚动,从右到左)的解决方案(在 Android 8 上测试)
类:AnimationAutoTextScroller.java
/**
* A Class for automatically scrolling text horizontally from Right to Left
* using TranslateAnimation so that the scrolling speed can be controlled -Suresh Kodoor
*/
public class AnimationAutoTextScroller {
Animation animator;
TextView scrollingTextView;
int duration = 50000; // default value
public AnimationAutoTextScroller(TextView tv, float screenwidth) {
this.scrollingTextView = tv;
this.animator = new TranslateAnimation(
Animation.ABSOLUTE, screenwidth,
Animation.RELATIVE_TO_SELF, -1f,
Animation.RELATIVE_TO_SELF, 0f,
Animation.RELATIVE_TO_SELF, 0f
);
this.animator.setInterpolator(new LinearInterpolator());
this.animator.setDuration(this.duration);
this.animator.setFillAfter(true);
this.animator.setRepeatMode(Animation.RESTART);
this.animator.setRepeatCount(Animation.INFINITE);
// setAnimationListener();
}
public void setDuration(int duration) {
this.duration = duration;
}
public void setScrollingText(String text) {
this.scrollingTextView.setText(text);
}
public void start() {
this.scrollingTextView.setSelected(true);
this.scrollingTextView.startAnimation(this.animator);
}
public void setAnimationListener() {
animator.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
// This callback function can be used to perform any task at the end of the Animation
}
public void onAnimationRepeat(Animation animation) {
}
});
}
}
布局 XML:(将 TextView 保留在 HorizontalScrollView 下)
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
app:layout_constraintBottom_toTopOf="@+id/hguide3"
app:layout_constraintEnd_toStartOf="@+id/vguide2"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toEndOf="@+id/vguide1"
app:layout_constraintTop_toBottomOf="@+id/hguide2">
<TextView
android:id="@+id/translateanimatortextviewscroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="0dp"
android:layout_marginEnd="0dp"
android:layout_marginLeft="0dp"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp"
android:text=""
android:singleLine="true"
android:focusable="true"
android:scrollHorizontally="true"
android:background="#000000ff"
android:textColor="#ff0000"
android:textSize="55dp"
android:textStyle="bold"
android:typeface="sans" />
</HorizontalScrollView>
活动:
TextView scrollertextview = findViewById(R.id.translateanimatortextviewscroller);
textscroller = new AnimationAutoTextScroller(scrollertextview, screenwidth);
textscroller.setScrollingText(scrollertext);
textscroller.setDuration(60000);
textscroller.start();