How to convert R.drawable String to R.drawable int

2020-07-27 05:02发布

问题:

I would like to R.drawable which is in a dynamic string format currently to an integer format.How can be it done.Please guide me with a snippet on this to resolve it.Thank you.

Integer[] images={R.drawable.apple,R.drawable.mango,R.drawable.banana};

回答1:

You can use this

public int[] getIntIds(Integer[] images){
    int[] temp = new int[images.length];
    String name;
    for(int i=0; i<= images.length; i++){
        name = getResources().getResourceEntryName(images[i]);
        temp[i] = getResources().getIdentifier(name , "drawable", getPackageName());
    }
    return temp;
}


回答2:

You can use this

String mDrawableName = "myimg";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

or

String imageName = "picture";
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID);