Search code examples
jsonkotlinarraylistandroid-animationlottie

How to add animation json files in an arraylist & display those animations on the screen when we iterate?


I have animation json file in the raw folder in res directory. I have made a data model , in which I want to store many properties with different data types.

Data Model

class ExerciseModel (
private var id:Int,
private var name:String,
private var isCompleted:Boolean,
private var isSelected:Boolean,
private var animationJson:String)

And then, I want to make an object of this class & store it in an ArrayList. as,

object Constants {

    fun defaultExerciseList():ArrayList<ExerciseModel>{
        val exerciseList=ArrayList<ExerciseModel>()
        val squat =ExerciseModel(1,"Squat",false,false, R.raw.squat.json)
        exerciseList.add(squat)

I have added the view in the activity_main.xml but it is not working.

<com.airbnb.lottie.LottieAnimationView
            android:id="@+id/exerciseAnimation"
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_centerInParent="true"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:lottie_autoPlay="true"
            app:lottie_fileName="jumping_jack.json"
            app:lottie_loop="true"
            app:lottie_speed="1" />

How to add the animation json file in the arraylist & make it display on the screen ?


Solution

  • update model code:-

    class ExerciseModel(
    var id: Int,
    var name: String,
    var isCompleted: Boolean,
    var isSelected: Boolean,
    var animationJson: Int)
    

    Add data in array:-

    val exerciseList=ArrayList<ExerciseModel>()
        val squat = ExerciseModel(1,"Squat",false,false, R.raw.squat)
        exerciseList.add(squat)
        val load = ExerciseModel(2,"Load",false,false, R.raw.load)
        exerciseList.add(load)
        val spring = ExerciseModel(3,"Spring",false,false, R.raw.spring)
        exerciseList.add(spring)
    

    Add this line for animation:-

    exerciseAnimation.setAnimation(exerciseList[0].animationJson) //0 is your animationfile position
    

    Update your xml code:-

    <com.airbnb.lottie.LottieAnimationView
                android:id="@+id/exerciseAnimation"
                android:layout_width="300dp"
                android:layout_height="300dp"
                android:layout_centerInParent="true"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:lottie_autoPlay="true"
                app:lottie_loop="true"
                app:lottie_speed="1" />