Android How to iterate over R.drawable object

I am trying to show animation frame by frame and I want to iterate through the drawings, so I don't have to type all of their names in case the number of frames increases.

However, I cannot find how to iterate over the drawings. I searched for the fair java part for the looping tutorials, but they all just printed stuff that (as far as I'm sure) shouldn't be used here.

Here's the relevant code (image names are dude1, dude2, ...):

   private void startAnimation(){
       animation = new AnimationDrawable();
       for (int i = 1; i < 4; i++) {
           animation.addFrame(getResources().getDrawable(R.drawable.dude(i)), 100);
       }
       animation.setOneShot(true);

       ImageView imageView = (ImageView) findViewById(R.id.img);
       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80, 90);
       params.alignWithParent = true;
       params.addRule(RelativeLayout.CENTER_IN_PARENT);      
       imageView.setLayoutParams(params);
       imageView.setImageDrawable(animation);
       imageView.post(new Starter());
   }

      

thank!

+3


source to share


3 answers


I think the last answer is plausible, but maybe:



for (int i=0; i <10;i++){
      animation.addFrame(
         getResources().getDrawable(getResources().getIdentifier("dude" + i,"drawable",
             getPackageName()),100);
}

      

+6


source


Try it. getResources()

context is needed.

for (int i=0;i<10;i++){
    animation.addFrame(getResources().getIdentifier("dude" + i,"drawable", getPackageName()),100);
}

      



Here I took 10 frames (i <10).

+2


source


I used Simon's answer to iterate through my blueprints which are named "c1" through "c54" and are put into an array. Here is the code I just used that works for me.

private void getDeckDrawables() {
    for (int i=0; i<54; i++){
        int j = i + 1;
        intArrDeck[i] = getResources().getIdentifier("c"+j,"drawable",getPackageName());
    }
}

      

I used to type them by hand, which took up too much space for my taste.

private void getDeckDrawables() {
    intArrDeck[0]=R.drawable.c1;
    intArrDeck[1]=R.drawable.c2;
    intArrDeck[2]=R.drawable.c3;
}

      

+1


source







All Articles