imgView.setImageResource(R.drawable.fl1); 

That way I can choose fl1 for image res. But instead of "1" I need to substitute the value of the variable i, i.e. if a:

i = 2, then I need to do - imgView.setImageResource (R.drawable.fl2);

i = 3, then I need to do - imgView.setImageResource (R.drawable.fl3);

etc.

How to achieve this effect?

ps The first thing that comes to mind (of course does not work :))

 imgView.setImageResource(R.drawable.fl + i); 

UPDATE1 Not one of the answers did not work. At @Gorets, the picture resource simply does not change, and at @ system29a and at @VladD :

 The type of the expression must be an array type but it resolved to Map<Integer,Integer> 

    3 answers 3

     int drawableResourceId = this.getResources().getIdentifier("R.drawable.fl"+i, "drawable", this.getPackageName()); imgView.setImageResource(drawableResourceId); 

      I do not know the specifics of Android, but I can assume the following:

      1. Make an array flValues[] and manually add all the values ​​of the variables fl {i} then your version is imgView.setImageResource(flValues[i])
      2. You can use Reflection, but I think this is too tricky. How to get the value of the field by its name, see here

        I don’t know if there is a native solution, but why not make a static Map<int, int> indexToResId and just write

         imgView.setImageResource(indexToResId[i]); 

        ?

        • Please give the code how to get this Map <> I just completely forgot how to use it, but right away it was impossible to figure it out again :( - kandi
        • @danpetruk: something like this: private final Map <Integer, Integer> indexToResId = new HashMap <Integer, Integer> () {{put (1, R.drawable.fl1); put (2, R.drawable.fl2); put (3, R.drawable.fl3); // etc. }}; If your indices are consecutive, starting from zero, you can simply array: private final List <Integer> indexToResId = Arrays.asList (R.drawable.fl0, R.drawable.fl1, R.drawable.fl2, R.drawable.fl3 / / etc.); - VladD