Handle drawables - by the name
I already know how to handle drawables like this:
final int[] imgSizeIds = new int[]{
R.drawable.zero,R.drawable.one,R.drawable.two,
开发者_高级运维 ...
};
and
setImageResource(imgSizeIds [ size ] );
in android. But what If I have an Array of Strings that is populated like this:
String[] names = new String[]{"oliver", "peter", "mike"};
and I would like to use Image oliver.jpg when The ROW Oliver is going to be handled.
Something like:
setImageResource(R.drawable. (AND HERE COMES "oliver") );
So the result will be:
setImageResource(R.drawable.oliver);
Two Arrays would not be the big problem but I also do not know how to put a string into the integer Array of drawables.. I cannot do something like:
final int[10] imgSizeIds;
String stringy = "oliver";
int[0] = "R.drawable." + stringy;
So that the 1st item in that array would be set to R.drawable.oliver
try this
int resid = getResources.getIdentifier("oliver" , "drawable", getPackageName());
setImageResource(resid);
setImageResource(R.drawable. (AND HERE COMES "oliver") );
So the result will be: setImageResource(R.drawable.oliver);
this will probably not happen.Because when you tell android to take a string specified in a String variable,it would take it as - "oliver" and put it like R.drawable."oliver"
or even though,if you would try putting it like - setImageResource("R.drawable."+ (AND HERE COMES "oliver") )
it will take it as a String like "R.drawable.oliver" which is after all a String variable and not appropriate to be passed in setImageResource()
method.
Be sure that R.drawable.imagename gives you int
, not a string.
See if below code helps-
String[] imgNames = new String[]{ "oliver", "apple", "car"};
and use this to use names from name string array-
ImageView imgvw = (ImageView) findViewById(getResources().getIdentifier(imgNames[index],"drawable",getPackageName()));
where index is position of item in string name array.
精彩评论