我想使用 var 来确定将哪张照片加载到图像视图中 - Kotlin

I want to use var to determine which photo to load into the image-view- Kotlin

我有一个 var 里面有一些食物(例如:比萨饼、汉堡等),我想用它 var 加载一个基于那个 var 值从我的 drawable 目录进入图像视图而不使用 when.

我有那些文件:pizza.png、burger.png

我想使用这样的东西:

var food = "pizza.png"
food_icon.setImageResource(R.drawable.food)//image is the pizza
food = "burger.png"
food_icon.setImageResource(R.drawable.food)//image is the burger

有办法吗?

为什么不这样做?

var food = R.drawable.pizza
food_icon.setImageResource(food)//image is the pizza
food = R.drawable.burger
food_icon.setImageResource(food)//image is the burger

例如,您可以使用对应于正确可绘制对象的枚举

enum class FoodTypes(private val value: Int) {
    PIZZA(R.drawable.pizza),   
    BURGER(R.drawable.burger);

    fun getValue(): Int = value
}

那你就可以这样使用了

var food = FoodTypes.PIZZA
food_icon.setImageResource(food.getValue())
food = FoodTypes.BURGER
food_icon.setImageResource(food.getValue())

如果我正确理解你的问题,你可以使用以下方法:

Resources resources = context.getResources();
final int resourceId = resources.getIdentifier("[your_drawable_name]", "drawable", context.getPackageName());
return resources.getDrawable(resourceId);

有了它,您可以指定您的 rawable 的名称并加载它。 如果您只需要 resourceId,您可以 return resourceId 而无需获取 drawable 本身。