我在drawable文件夹中有这些图像:
image_1.png
image_2.png
image_3.png
...
image_n.png
我有一个像这样的id属性的PlayerDTO:
public class PlayerDTO implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
//... getters and setters
}
我需要在播放器ID和相应的图像之间建立匹配,以便在ImageView中设置它。 e.g:
player id = 1. It's image is image_1.png
player id = 2. It's image is image_2.png
...
player id = n. It's image is image_n.png
这是相同的,但这不是动态的:
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(R.drawable.image_1);
如何以编程方式动态完成此操作?
答案 0 :(得分:1)
如果您的意思是尝试以编程方式获取资源名称,那么就这样:
int[] drawableId = new int[totalNumberOfImages];
String drawableName;
for (int n = 1; n < totalNumberOfImages; n++) {
drawableName = "image_" + n;
drawableId[n] = getResources().getIdentifier(drawableName, "drawable", getPackageName());
}
这将为您提供一系列可绘制的ID。
要获得直接关联,您可以使用SparseIntArray,例如:
int drawableId;
String drawableName;
SparseIntArray playerImages = new SparseIntArray(totalNumberOfPlayers);
for (int n = 1; n < totalNumberOfPlayers; n++) {
drawableName = "image_" + n;
drawableId = getResources().getIdentifier(drawableName, "drawable", getPackageName());
playerImages.put(n, drawableId);
}