gpt4 book ai didi

android - List 中的可绘制图像未显示在 Android Studio 上。 ( Kotlin )

转载 作者:行者123 更新时间:2023-11-29 15:33:27 24 4
gpt4 key购买 nike

更新 MainFragment.kt

private val FoodList = listOf(
Food(R.drawable.burget,"Biriyani", 100),
Food(R.drawable.coke,"Fried Rice", 80),
Food(R.drawable.eggbiriyani,"Idli", 30),
Food(R.drawable.burget,"Masala Dosa", 40),
Food(R.drawable.icecream,"Ice Cream", 40),
Food(R.drawable.burget,"Apple Juice", 50),
Food(R.drawable.burget,"Orange Juice", 50),
Food(R.drawable.burget,"Mango Juice", 50)
)

更新数据类 Food

data class Food(val image: Int, val name: String, val price: Int)

更新了 FoodViewHolder.kt

class FoodViewHolder (inflater: LayoutInflater, parent: ViewGroup) :
RecyclerView.ViewHolder(inflater.inflate(R.layout.list_item, parent, false)) {
private var FoodName: TextView? = null
private var FoodPrice: TextView? = null


init {
FoodName = itemView.findViewById(R.id.food_name)
FoodPrice = itemView.findViewById(R.id.food_price)
}

fun bind(food: Food) {
FoodName?.text = food.name
FoodPrice?.text = food.price.toString()
}
}

更新的 FoodAdapter.kt

这是我的适配器代码,但我不知道在哪里放置更改。我在 FoodViewHolder 中使用 bind 来访问 data class Food 但我无法找到正确的代码来访问图像。

class FoodAdapter(private val list: List<Food>)
: RecyclerView.Adapter<FoodViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodViewHolder {
val inflater = LayoutInflater.from(parent.context)
return FoodViewHolder(inflater, parent)
}

override fun onBindViewHolder(holder: FoodViewHolder, position: Int) {
setImageResources(list[position].image)
val food: Food = list[position]
holder.bind(food)
}

private fun setImageResources(image: Int): Int {
return R.id.food_image
}

override fun getItemCount(): Int = list.size

}

请帮助我使用 kotlin 代码。这些图像没有显示我根据主要 fragment 中的可绘制对象提到的图像。提前致谢!!

最佳答案

您不能将图片资源设置为字符串。

像这样创建一个列表:

private val FoodList = listOf(
Food(R.drawable.burget,"Biriyani", 100),
Food(R.drawable.coke,"Fried Rice", 80),
Food(R.drawable.eggbiriyani,"Idli", 30),
Food(R.drawable.burget,"Masala Dosa", 40),
Food(R.drawable.icecream,"Ice Cream", 40),
Food(R.drawable.burget,"Apple Juice", 50),
Food(R.drawable.burget,"Orange Juice", 50),
Food(R.drawable.burget,"Mango Juice", 50)
)

您的数据模型应如下所示

data class Food(val image: Int, val name: String, val price: Int)

像这样在适配器中设置图像

 FoodImage.setImageResources(food.image) 

关于android - List 中的可绘制图像未显示在 Android Studio 上。 ( Kotlin ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com