skip to Main Content

I’m trying to use a random number generator to pick between one of 10 different animations to run using a Lottie implementation. I’ve named the animations animation1 to animation10. When directly inputing one of the animations like this there’s no issue:

animationView.setAnimation(R.raw.animation2);

but the app keeps on crashing when inputing it like this:

LottieAnimationView animationView = findViewById(R.id.animationViewer);
randNumber = rand.nextInt(10) + 1;

animationView.setAnimation("R.raw.animation" + randNumber);

With the cause being:

Caused by: java.io.FileNotFoundException: R.raw.animation2

3

Answers


  1. Chosen as BEST ANSWER

    Found this to be the best solution

    Resources resources = context.getResources();
    String animationDir = "animation" + randNumber;
    final int resourceId = resources.getIdentifier(animationDir, "raw", context.getPackageName());
    context.getPackageName();
    
    animationView.setAnimation(resourceId);
    

  2. You can’t do that because setAnimation() requires a ResID and not a string.

    Instead, you can use an Array like this

    <integer-array name="animations">
        <item>@anim/animation1</item>
        <item>@anim/animation2</item>
    </integer-array>
    

    And then, you can use your random number.

    Login or Signup to reply.
  3. you are trying to send a resource id as a string
    you can create an array of resources or the easiest but not the cleanest way is :

     animID = when(randNumber){
    

    1 -> {R.raw.animation1}
    2 -> {R.raw.animation2}
    .
    .
    .
    .
    10 -> {R.raw.animation10}
    }

    animationView.setAnimation(animID);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search