TransitionDrawable的使用

作用

实现淡入淡出的效果

仅支持两张图片

使用步骤

  1. 定义TransitionDrawable.xml文件
  2. 获取TransitionDrawable对象
  3. 使用
    1. 开始:transition.startTransition(1000)
    2. 反转:transition.reverseTransition(1000)
    3. 重置: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)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值