iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Android】View の Background をアニメーションさせる

本日はタイトルの通り、AndroidViewbackground リソースをアニメーションさせながら変更する方法を紹介したいと思います👩‍🌾

それではやっていく

まずは、アニメーションの初期状態の drawable とアニメーション後の drawable をそれぞれ定義しておきます。今回は border_radius_12dp.xml という drawable ファイルを初期値として border_green_radius_12dp というファイルをアニメーション後の値として定義しました。

次に上記で作成したファイルを使用して、アニメーションのための drawable を下記のように作成します。

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/border_radius_12dp" />
    <item android:drawable="@drawable/border_green_radius_12dp" />
</transition>

作成したアニメーションの drawablebackground としてレイアウトに設定します。

        android:background="@drawable/animation_drawable"

最後に、View クラスから下記のように startTransition を呼び出すことで background をアニメーション付きで変更させることができます。

        val transition = textView.background as TransitionDrawable
        transition.startTransition(150)

TestDrawable は2つの drawable リソースをクロスフェードさせる drawable オブジェクトです。ちなみに、android:background で設定されている drawableTransitionDrawable でない場合はクラッシュするので注意が必要です。 TestDrawable について詳しく知りたい場合は下記を参照してください。

developer.android.com

developer.android.com

という感じで本日も以上になります。

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com