作用
实现淡入淡出的效果
仅支持两张图片
使用步骤
- 定义TransitionDrawable.xml文件
- 获取TransitionDrawable对象
- 使用
- 开始:transition.startTransition(1000)
- 反转:transition.reverseTransition(1000)
- 重置:transition.resetTransition()
注意:重置后只能调用开始方法,这时如果调用反转方法会出现显示异常!
code
expand_collapse.xml
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:drawable/checkbox_off_background"/>
<item android:drawable="@android:drawable/checkbox_on_background"/>
</transition>
kotlin
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.res.ResourcesCompat
class MainActivity : AppCompatActivity() {
private lateinit var constraintLayout: LinearLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val transition = ResourcesCompat.getDrawable(
resources,
R.drawable.expand_collapse,
null
) as TransitionDrawable
// Instantiate an ImageView and define its properties
val i = ImageView(this).apply {
setImageDrawable(transition)
contentDescription = "ic_launcher_foreground"
// set the ImageView bounds to match the Drawable's dimensions
adjustViewBounds = true
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
}
val b = Button(this).apply {
text = "开始"
setOnClickListener {
transition.startTransition(1000)
}
}
val b1 = Button(this).apply {
text = "反转"
setOnClickListener {
transition.reverseTransition(1000)
}
}
val b2 = Button(this).apply {
text = "重置"
setOnClickListener {
transition.resetTransition()
}
}
// Create a ConstraintLayout in which to add the ImageView
constraintLayout = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
// Add the ImageView to the layout.
addView(i)
addView(b)
addView(b1)
addView(b2)
}
// Set the layout as the content view.
setContentView(constraintLayout)
}
}