15
16

More than 5 years have passed since last update.

AndroidアニメーションでViewを操作する

Last updated at Posted at 2019-02-24

やりたいこと

画面を表示すると、説明View2秒表示し、1秒かけて透過しながら消えていく。
という動きを実装したい。

方法3つ

以下を使ってViewをアニメーションを実装する。

  • ViewPropertyAnimator
  • View Animation (anim)
  • ObjectAnimator (animator)

これらを1つずつ使い同じ動作を実装する。

ViewPropertyAnimator

特徴は、Viewに直接コードで記述できるためお手軽だ。

view.run {
    visibility = View.VISIBLE
    postDelayed({
        animate().alpha(0f).setDuration(1000).withEndAction { visibility = View.GONE }
    }, 2000)
}

postDelayedで2秒待機させ、animate()で透過をイジっていく。
withEndActionは言葉のとおり最後に行うアクションね。

コードだとサッと試せて楽だが、アニメーションが複雑になっていくと記述もカオスになっていくのが難点。

View Animation (anim)

animフォルダにxmlでアニメーションを記述し、ソースで読み込む

view.run {
     visibility = View.VISIBLE
     val animation = AnimationUtils.loadAnimation(context, R.anim.alpha_fadeout)
     postDelayed({ startAnimation(animation) }, 2000)
 }
anim/alpha_fadeout.xml
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fillAfter="true"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toAlpha="0.0"
    />

AnimationUtilsを使ってxmlを読み込んでいる。
xmlを作成するのは手間だが、xmlを見るとアニメーションの流れが分かりやすいし、複雑になっても混乱しない。

ObjectAnimator (animator)

ObjectAnimatorは直接ソース内にクラスを宣言してアニメーションを記述する事も可能だが、今回はxmlで書いてみる。

AnimatorInflater
        .loadAnimator(context, R.animator.alpha_fadeout)
        .run {
            setTarget(view)
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationRepeat(anim: Animator?) {}

                override fun onAnimationStart(anim: Animator?) {
                    view.visibility = View.VISIBLE
                }

                override fun onAnimationEnd(anim: Animator?) {
                    view.visibility = View.GONE
                }

                override fun onAnimationCancel(anim: Animator?) {}
            })
            start()
        }
animator/alpha_fadeout.xml
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:ordering="sequentially"
    >
    <objectAnimator
        android:startOffset="2000"
        android:duration="1000"
        android:propertyName="alpha"
        android:valueTo="0f"
        />
</set>

AnimatorInflater.loadAnimatorでアニメーションxmlを読み込んでいる。
また、addListenerでアニメーション前/後にViewの表示を操作している。
listenerに関しては、もっと短く記述できる方法があるが、今回はとりあえずそのまま使う。

備考

自分の中でなんとなく使っていたアニメーションを記事に書き出すことで理解できた。

アニメーションを書くとき、コード(java/kotlin)で直接書く派とxmlで書く派に分かれるとはず。

コードではサクッと書けるが、複雑になると見づらい。
XMLではファイルを作るのが面倒だが、再利用できるし複雑になっても強い。

まぁ好きな方で書けばいいさー

参考

Animation resources  |  Android Developers https://developer.android.com/guide/topics/resources/animation-resource

15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16