LoginSignup
0
1

More than 3 years have passed since last update.

LottieをリソースIDでデータバインディングしてコードをスッキリ

Posted at

Lottieは簡単に素敵なアニメーションを追加できるAirbnbのライブラリです。
更に使いやすくresourceIdでデータバインディングできるようにカスタムBindingAdapterを用意して使ってみました。

Lottie

カスタムBindingAdapterを作成

LottieAnimationViewBindingAdapter.java

import androidx.annotation.RawRes;
import androidx.databinding.BindingAdapter;
import androidx.databinding.BindingMethod;
import androidx.databinding.BindingMethods;

import com.airbnb.lottie.LottieAnimationView;

@BindingMethods({
        @BindingMethod(type = com.airbnb.lottie.LottieAnimationView.class, attribute = "lottie_rawRes", method = "setAnimation"),
})
public class LottieAnimationViewBindingAdapter {

    @BindingAdapter("lottie_rawRes")
    public static void setAnimation(LottieAnimationView view, @RawRes final int rawRes) {
        view.setAnimation(rawRes);
        view.playAnimation();
    }
}

ViewModelでResId用のLiveDataを作成

HogeViewModel.kt

val animationResId: LiveData<Int> = Transformations.map(hoge) {
        when {
            hoge.value!! > THRESHOLD -> R.raw.rocket_in_space
            else -> R.raw.lighthouse
        }
    }

レイアウトにバインド

hoge_fragment.xml

<data>
        <variable
            name="vm"
            type="com.hoge.HogeViewModel" />
    </data>

...

<com.airbnb.lottie.LottieAnimationView
            android:id="@+id/animationView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:lottie_autoPlay="true"
            app:lottie_loop="true"
            app:lottie_rawRes="@{vm.animationResId}" />
0
1
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
0
1