一、前言
有时候要实现跑马灯效果,但是网上的跑马灯实现方式都比较复杂,如果要求不高的话使用属性动画会简单一些。主要有以下优缺点:
优点:
- 代码简单,方便修改
- 动画过程可以进行控制
- 动画结束后可以回归原始位置(或者其它位置)
缺点:
- 没有办法一行文字,两端各显示一半,比如已经移动了一半时候,末尾不会出现另外一半
二、代码
使用HorizontalScrollView 包裹,防止文字显示不完
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<HorizontalScrollView
android:layout_width="50dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1234567890"
android:lines="1"/>
</HorizontalScrollView>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始动画"
android:onClick="onClick"
app:layout_constraintTop_toBottomOf="@+id/tv"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<Button
android:id="@+id/cancel_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="撤销动画"
android:onClick="onClick"
app:layout_constraintTop_toBottomOf="@+id/btn"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
class MainActivity : AppCompatActivity() {
private var textView: TextView ?= null
private var animator: ObjectAnimator ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textView = findViewById(R.id.tv)
}
fun onClick(view: View){
when(view.id){
R.id.btn -> {
startAnimation()
}
R.id.cancel_btn -> {
cancelAnimation()
}
}
}
private fun startAnimation(){
val right = textView!!.right
val selfWith = textView!!.width
Log.d("YM","----->right:$right")
Log.d("YM","----->selfWith:$selfWith")
var times = 1
animator = ObjectAnimator.ofFloat(textView!!, "translationX", 200f,-500f).apply {
duration = 2000
repeatCount = ValueAnimator.INFINITE
addListener{
doOnRepeat {
times++
if (times > 1){
setFloatValues(0f,-500f)
}
Log.d("YM","---->重复次数:$times")
}
}
start()
}
}
private fun cancelAnimation(){
animator?.cancel()
animator?.start()
animator?.cancel()
textView!!.translationX = 0f
}
}
|