49

I have an array like this.

int image[] = {R.drawable.d002_p001,R.drawable.d002_p002,R.drawable.d002_p003,
                   R.drawable.d002_p004,R.drawable.d002_p005,R.drawable.d002_p006};

Right now I have 6 images so I am statically given the name.

If I have some 50 images I cant give each and every file name in array so it needs to be dynamic how can I achieve this.

yrazlik
  • 10,411
  • 33
  • 99
  • 165
Goofy
  • 6,098
  • 17
  • 90
  • 156

10 Answers10

117

You can use getIdentifier()

for (int j = 1; j < 6; j++) {
   Drawable drawable = getResources().getDrawable(getResources()
                  .getIdentifier("d002_p00"+j, "drawable", getPackageName()));
}
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
13

You can also use this:

int res = getResources().getIdentifier("<your pakecgename>:drawable/abc", null, null);
Julian
  • 20,008
  • 17
  • 77
  • 108
Sunil_Suthar
  • 1,094
  • 1
  • 10
  • 20
7

Something like this could work

Field[] drawables = android.R.drawable.class.getFields();
for (Field f : drawables) {
    try {
        System.out.println("R.drawable." + f.getName());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
blessanm86
  • 31,439
  • 14
  • 68
  • 79
5

Use the following line for getting drawable dynamically:

Drawable drawable = this.getResources().getDrawable(R.drawable.yourDrawableID);

This will give you the desired Drawable.

King of Masses
  • 18,405
  • 4
  • 60
  • 77
SAMD
  • 421
  • 1
  • 3
  • 7
  • `yourDrawableID` is actual `ID` value that you have specified for element in your layout(xml) file. – Uniruddh Apr 25 '14 at 13:18
2
public static Drawable getImage(Context context, String name) {
        return context.getResources().getDrawable(context.getResources().getIdentifier(name, "drawable", context.getPackageName()));
}
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
2
String[] names = new String []{"yout names..."};
    for(String n: names) {
        Utils.GetDrawableByName(n,this);
    }

public class Utils {
public static Drawable GetDrawableByName(String name,Activity context){
    Resources res = context.getResources();
    return res.getDrawable(res.getIdentifier(name,"drawable",context.getPackageName()));
    }
}
Abbath
  • 1,002
  • 13
  • 30
1
package com.example.studio.snakes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

int[] dices = {
        R.drawable.one,
        R.drawable.two,
        R.drawable.three,
        R.drawable.four,
        R.drawable.five,
        R.drawable.six,
};


public void rollTapped(View view){
 Log.i("Button","Button Tapped");
    Random rand = new Random();
    int randomnum = rand.nextInt(6);
    Log.i("Random","Random number is " + randomnum );
    ImageView dice=findViewById(R.id.imageView2);
    dice.setImageResource(dices[randomnum]);


}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
}
  • Here i have created array dices for images in drawable folder.And i have accessed images randomly by the generation of random variable titled as randnum( from the code).Here i am keep on changing already existing image(id is imageView2 from the code) for each random number.Whenever we tap a buttom images will be randomly generated – Anwar shanib Mar 09 '18 at 01:49
0

We can take advantage of Imageview setImageResource as this will efficient than drawable seems, refer below code for the same.

The below code can be used to show the image like gif incase if you have the multiple split image of gif. Just split the gif into individual png from a online tool and put image in the drawable like the below order

image_1.png, image_2.png, etc.

Have the handler to change the image dynamically.

int imagePosition = 1;
    Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            public void run() {
                updateImage();
            }
        };




    public void updateImage() {

                appInstance.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
                        gifImageViewDummy.setImageResource(resId);
                        imagePosition++;
    //Consider you have 30 image for the anim
                        if (imagePosition == 30) {
//this make animation play only once
                            handler.removeCallbacks(runnable);

                        } else {
    //You can define your own time based on the animation
                            handler.postDelayed(runnable, 50);
                        }

//to make animation to continue use below code and remove above if else
// if (imagePosition == 30)
//imagePosition = 1;
// handler.postDelayed(runnable, 50);
// 
                    }
                });
              }
Lakshmanan
  • 1,671
  • 2
  • 26
  • 42
0

Extension function for Kotlin

fun Activity.getDrawable(drawableName: String): Drawable? {
    val drawableId = resources
        .getIdentifier(drawableName, "drawable", packageName)

    if (drawableId != 0) {
        return ResourcesCompat.getDrawable(resources, drawableId, null)
    }
    return null
}
Chirag Prajapati
  • 25
  • 1
  • 1
  • 7
-10

use this code to create array and later use that array

int NUM_OF_IMAGES = 50;
String images[] = new String[NUM_OF_IMAGES];
for (int i =0; i < NUM_OF_IMAGES; i++) {
    images[i] = "R.drawable.d002_p00" + i;
}

main thing you have to take care is the file name must start with "d002_p00" this and after there is digit 1 to 50

ONE
  • 567
  • 7
  • 15
dilipkaklotar
  • 1,469
  • 3
  • 20
  • 28
  • 1
    its showing me error dude "R.drawable.d002_p00" +i; cannot convert from int to string – Goofy Feb 06 '12 at 07:26
  • 5
    this answer is really bad... have you learned java?? A `String` can not be assigned to a int variable... and a int cannot be added to an string without using `String.valueof()`... – maysi Aug 30 '13 at 18:44
  • Mr.dilipkaklotar some code wrong so change our here and update your post – Ramani Hitesh Nov 16 '17 at 06:08