假设我们有:
ImageView imageView_A = findViewById(R.id.imageview_dhze);
ImageView imageView_B = findViewById(R.id.imageview_dhhkjhkze);
ImageView imageView_C = findViewById(R.id.imageview_dhkhkjze);
ImageView imageView_D = findViewById(R.id.imageview_dhhuihuybze);
我想制作一个这样的函数:
changeImages(String NAME) {
imageView_1_NAME.setImageResource(R.drawable.img);
imageView_2_NAME.setImageResource(R.drawable.img);
imageView_3_NAME.setImageResource(R.drawable.img);
}
例如,我可以像这样使用它:
changeImage("A");
获得:
imageView_1_A.setImageResource(R.drawable.img);
imageView_2_A.setImageResource(R.drawable.img);
imageView_3_A.setImageResource(R.drawable.img);
有可能吗?我怎么能这样做?
答案 0 :(得分:1)
您可以将所有ImageView放在HashMap中,如下所示:
HashMap<String, ImageView> imageViews = new HashMap<>();
然后将ImageViews添加到HashMap:
imageViews.put("A", imageView_A);
imageViews.put("B", imageView_B);
...
然后你的功能看起来像这样:
private void changeImage(String name) {
imageViews.get(name).setImageResource(R.drawable.img);
}
在这种情况下,只有当HashMap包含具有相同String名称值的键时,才应调用changeImage()。如果您不确定是否存在密钥,则需要首先检查imageViews.containsKey(名称)。
答案 1 :(得分:0)
你可以这样做:
Demos
答案 2 :(得分:-1)
我认为你要找的是这样的
fun changeImage(which: String) {
when(which) {
"a" -> imageView_A.setImageResource(R.drawable.img)
"b" -> imageView_B.setImageResource(R.drawable.img)
"c" -> imageView_C.setImageResource(R.drawable.img)
"d" -> imageView_D.setImageResource(R.drawable.img)
else -> throw IllegalArgumentException("Unknown image view")
}
}
答案 3 :(得分:-1)
int[] images = {R.id.imageA,R.id.imageB,R.id.imageC,R.id.imageD,R.id.imageE};
int[] drawables = {R.drawable.imageA,R.drawable.imageB,R.drawable.imageC,R.drawable.imageD,R.drawable.imageE};
for(int i=0;i<5;i++)
{
findViewById(images[i]).setImageResource(drawables[i]);
}
这更容易。