<TextView
android:id="@+id/shimmerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="流光效果"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:gravity="center"/>
private fun setAnim() {
val shimmerTextView = binding.shimmerTextView
// 创建 LinearGradient
val width = shimmerTextView.paint.measureText(shimmerTextView.text.toString())
val gradient = LinearGradient(
0f, 0f, width, 0f,
intArrayOf(0x22ffffff, 0xffffffff.toInt(), 0x22ffffff),
floatArrayOf(0f, 0.5f, 1f),
Shader.TileMode.CLAMP
)
shimmerTextView.paint.shader = gradient
// 创建动画来平移渐变效果
val animator = ValueAnimator.ofFloat(0f, width)
animator.addUpdateListener { animation ->
val value = animation.animatedValue as Float
val matrix = Matrix()
matrix.setTranslate(value, 0f)
gradient.setLocalMatrix(matrix)
shimmerTextView.invalidate()
}
animator.duration = 1500L
animator.repeatCount = ValueAnimator.INFINITE
animator.start()
}