Kotlin 如何改变文字或按钮背景颜色以及相关动画效果
我们可能会遇到这样一类问题,当某一条件被触发后,文字或按钮背景颜色发生变化,行程类似报警的效果。这里介绍一种方式,适用于改变文字或按钮的背景颜色,并可以按照要求进行循环播放。
1 activity_main.xml
这里在前端,我们先新建一个按钮和一个TextView。
<Button
android:id="@+id/pushButton"
android:layout_width="150dp"
android:layout_height="150dp"
android:text="Press"
android:textColor="@color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.344" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:text="案例1:按下下面这个按钮后,\n触发声光报警"
android:textSize="20dp"
app:layout_constraintBottom_toTopOf="@id/pushButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent" />
我们这个例子的目的是按下按钮后,按钮和文字背景都会发生颜色上的变化。
2 MainActivity.kt
@SuppressLint("ClickableViewAccessibility", "ResourceType")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 当我们按下按钮后触发
pushButton.setOnTouchListener { _, event ->
// 按钮的颜色会从红色和白色之间进行切换,总的时常为7秒
animateColorValue(pushButton, Color.RED, Color.WHITE, 7000L)
// 按钮上面的文字背景颜色会从绿色和黄色之间进行切换,总的市场为3秒
animateColorValue(textView, Color.GREEN, Color.YELLOW, 3000L)
true
}
}
// 颜色切换功能
private fun animateColorValue(view: View, colorFrom: Int, colorTo: Int, totalDuration: Long) {
val colorAnimation =
ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo, colorFrom, colorTo, colorFrom, colorTo, colorFrom)
colorAnimation.duration = totalDuration
colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
colorAnimation.start()
}
当我们按下 pushButton
按钮后,触发两个函数:animateColorValue(pushButton, Color.RED, Color.WHITE, 7000L)
和 animateColorValue(textView, Color.GREEN, Color.YELLOW, 3000L)
。对应按钮背景红色和白色颜色转换,持续7秒和文字背景绿色和黄色颜色转换,持续3秒。