しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

AnimationDrawableでアニメーションを作る

AnimationDrawableでアニメーションを作れるようなので試してみました。

プロジェクトを作ったらまず下のようなアニメーション画像2枚を追加します。

次はdrawableフォルダ内に下のようなtest_animation.xmlを作成します。
android:oneshotは1回だけか繰り返すかを決めるものでandroid:durationはアニメーションの時間(ミリ秒単位)になります。

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">
    <item android:drawable="@drawable/test1" android:duration="200" />
    <item android:drawable="@drawable/test2" android:duration="200" />
</animation-list>

次にレイアウトファイルでImageViewを設置します。
背景画像は先程作成したアニメーションファイルにします。

<ImageView
    android:id="@+id/image_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/test_animation" />

最後にアニメーションをスタートする処理を書けば完了です。
isRunningの時はアニメーションを開始できないので、毎回stopしています。

binding.imageView.setOnClickListener {
    val animate = it.background as? AnimationDrawable
    if (animate!!.isRunning)
        animate.stop()
    animate?.start()
}