Android 使用 RotateDrawable 实现箭头动画

2021-02-02  本文已影响0人  小强开学前

知识点


最终效果


最终效果.gif

xml代码

TextView设置文字及背景色以及代码设置drawableStart、drawableEnd,Button用于设置点击事件。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <import type="com.john.test.FAndroid" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <TextView
            android:id="@+id/test_text_view"
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:background="@color/colorAccent"
            android:layout_gravity="center"
            android:padding="12dp"
            android:text="123123123" />

        <Button
            android:id="@+id/test_click"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="200dp"
            android:text="click" />
    </LinearLayout>
</layout>

rotate/xml

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/ic_drop_down"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360" />

Kotlin 代码

注意,mutate()方法非常重要,它是一个不可逆的操作,可以将drawable�实例状态独立出来。

class TestActivity : AppCompatActivity() {
    private lateinit var mBinding:ActivityTestBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_test)
        mBinding.lifecycleOwner = this
        
        val d1 = ResourcesCompat.getDrawable(resources, R.drawable.rotate, null) as RotateDrawable
        val d2 = ResourcesCompat.getDrawable(resources, R.drawable.rotate, null) as RotateDrawable
        Log.d("lq", "is drawable the same: ${d1 == d2}")
        d1.mutate()
        mBinding.testTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(d1, null, d2, null)

        var chose = true
        mBinding.testClick.setOnClickListener {
            if (chose) {
                ObjectAnimator.ofInt(d1, "level", 0, 5000).setDuration(300).start()
                ObjectAnimator.ofInt(d2,"level",5000,10000).setDuration(300).start()
            } else {
                ObjectAnimator.ofInt(d2,"level",0,5000).setDuration(300).start()
                ObjectAnimator.ofInt(d1, "level", 5000, 10000).setDuration(300).start()
            }
            chose = !chose
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读