AnimatedVectorDrawableに必要なanimatorやdrawableを用意したのにうまく動かない時の確認ポイントをまとめます。
1. Animatableのstart()を呼んでいるか
AnimatedVectorDrawableは明示的にstart()を呼ばないと動きません。
こんな感じでstartメソッドを呼ぶようにしましょう。
private void startAnimation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// ImageViewがselect状態かどうかで判定してセットするAnimatedDrawableを決める
int drawableResId = imgPlayToPause.isSelected()
? R.drawable.ic_pause_to_play
: R.drawable.ic_play_to_pause;
// Drawableをセットする。setImageResource()だと動かないので注意
Drawable drawable = getDrawable(drawableResId);
imgPlayToPause.setImageDrawable(drawable);
if (drawable instanceof Animatable) {
Animatable animatable = (Animatable) drawable;
// アニメーション中だったらいったん止める
if (animatable.isRunning()) {
animatable.stop();
}
// アニメーションを開始
animatable.start();
}
// 次にタップしたら逆方向のアニメーションを実行するためにselect状態を切り替える
imgPlayToPause.setSelected(!imgPlayToPause.isSelected());
}
}
2. AnimatedVectorDrawableのxmlのtarget nameとVectorDrawableのxmlのpath nameが一致しているか
例えばこんな感じのVectorDrawableの時、pathの android:name
が重要です。
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportHeight="48.0"
android:viewportWidth="48.0">
<path
android:name="play"
android:fillColor="@color/grey600"
android:pathData="@string/path_play" />
</vector>
上記のnameと、AnimatedVectorDrawableの android:name
が一致しているかを確認しましょう。このケースでは play
を一致させておかないと動きません。
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ic_play_arrow_grey_600_24dp">
<target
android:name="play"
android:animation="@animator/anim_play_to_pause" />
</animated-vector>
以上です。何か他にあれば追記します。