int i = 1;
String IMG = "pic";
IMG = IMG + Integer.toString(i);
i = i + 1;
imageview1.setImageResource(R.drawable.IMG);
R.drawable.IMG where IMG is a variable.
This is wrong. What would the right way? I want to change a imageview from pic1 to picN.
int[] images = new int[]{R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};
This is better, but How can I insert a vector element into a imageview? Sorry for my bad english level :)
This can be accomplished by using
int resourceId = getResources().getIdentifier("pic" + i, "drawable", getPackageName());
imageview1.setImageResource(resourceId);
This is proven to be fairly slow. A better option might be to keep an array of your drawable IDs and loop through that..
int[] drawables = new int[] { R.drawable.pic1, R.drawable.pic2 };
The identifiers that identify the resources in your app are not a series of sequential numbers. Create an array of the images you've added, eg
int[] images = new int[]{R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};
and increment the index in that instead?
与@dymmeh提供的解决方案类似,您也可以使用Java Reflection来执行此操作,但是我怀疑它也可能很慢。
int resId = R.drawable.getClass().getField("pic" + i).getInt(R.drawable);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.