【问题标题】:Add Image Into RecyclerView Android Using Kotlin使用 Kotlin 将图像添加到 RecyclerView Android
【发布时间】:2018-09-26 09:21:44
【问题描述】:

如何使用 kotlin 将可绘制对象中的图像动态添加到回收站视图中?这是我的 MainActivity.kt

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    binding.get = Get()

    //parse array klaxon
    var products = Klaxon().parseArray<ProductData>(addProducts())
    if (!products!!.isEmpty()) {
        product_list.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        product_list.hasFixedSize()
        product_list.adapter = ProductAdapter(products, { item: ProductData-> item })
    }
}

private fun addProducts(): String {
    return application.assets.open("product_data.json").bufferedReader().use{
        it.readText()
    }
}

private fun read(): String {
    return application.assets.open("text.json").bufferedReader().use{
        it.readText()
    }
}

fun Get() : Data {
    val data = Klaxon()
            .parse<Data>(read())
    if(data == null) return Data(
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            ""
    )
    return data
}
}

这是我的适配器ProductAdapter

class ProductAdapter (var productList: List<ProductData>, var clickListener: (ProductData) -> Unit) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    var v = LayoutInflater.from(parent.context).inflate(R.layout.product_lists_item, parent, false)
    return ListHolder(v)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    (holder as ListHolder).bind(productList[position], clickListener)
}

override fun getItemCount() = productList.size

class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(_list: ProductData, clickListener: (ProductData) -> Unit) {
        itemView.product_item.text = _list.product_name
        itemView.setOnClickListener { clickListener(_list) }
    }
}
}

这是我的数据类,ProductData.kt

data class ProductData (
    var product_name: String
//do I need to declare the image here?
)

这里我使用 JSON 获取数据,product_data.json

[ {
"product_name": "Flexible Hose Tangki Air Penguin",
"product_image": "flexible_hose_tangki_air_penguin_1_fu.jpg"
  },
  {
    "product_name": "Foot Valve / Tusen Klep Tangki Air Penguin",
    "product_image": "foot_valve_tusen_klep_tangki_air_penguin_1_fu.jpg"
  },
  {
    "product_name": "Gasket Aksesoris Tangki Air Penguin",
    "product_image": "gasket_aksesoris_tangki_air_penguin_1_fu.jpg"
  }
]

我能够显示回收站视图,但不能显示图像数据。我需要将图像放在产品名称的顶部。 我应该用毕加索吗?或不?提前致谢。

【问题讨论】:

  • 是的,使用毕加索,并在模型中定义位图。
  • 获取图片文件怎么样?我是毕加索的新手,所以我不知道如何使用 kotlin。
  • 你是从服务器获取图片 url 还是从 drawable 添加图片?
  • 我需要先从drawable中获取图片
  • 下面的解决方案可以试试。

标签: android json kotlin


【解决方案1】:

在 ProductData 中将 resourceId 添加为 Int

    data class ProductData (
var productName: String , 
var drawableResourceId: Int // will be R.drawable.my_resource
)

并在您的列表适配器中添加:

itemView.product_icon.setImageDrawable(ContextCompat.getDrawable(context, _list.drawableResourceId)

您需要在适配器中添加上下文

【讨论】:

  • 啊,忘了说,我是用json获取图片的,不是直接从xml获取的。
【解决方案2】:

JSON

[ { "product_name": "Flexible Hose Tangki Air Penguin", "product_image": "android" }, { "product_name": "Foot Valve / Tusen Klep Tangki Air Penguin", "product_image": "ios" }, { "product_name": "Gasket Aksesoris Tangki Air Penguin", "product_image": "blackberry" } ]

如果您想显示可绘制的图像,请在您的 ProductData 类中再添加一个字段

data class ProductData (
var product_name: String , 
var product_image: String
)

在 ProductData 类中添加数据,如下所示

var androidProduct =  ProductData(productnamefromjson,productimagenamefromjson)

通过 ProductAdapter 类中的构造函数传递上下文参数 -

class ProductAdapter (var context: Context,var productList: List<ProductData>, var clickListener: (ProductData) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() 

更改此行
product_list.adapter = ProductAdapter(products, { item: ProductData-> item })

product_list.adapter = ProductAdapter(this@MainActivity,products, { item: ProductData-> item })

在 imageview 中设置图像,如下所示 -

val resources = context.getResources()
val resourceId = context.resources.getIdentifier(_list.product_image), "drawable",
            context.getPackageName())
itemview.imageview.setImageDrawable(resources.getDrawable(resourceId))

【讨论】:

  • 在 android.widget 上找不到值类型为 int 的属性 'android:src' 的 getter - 这里出现错误,src 属性不允许 int?
  • 我认为你正在这样做 - itemview.imageview..setImageDrawable(_list.product_image) 。您需要使用 setImageResource()
  • 我忘了说,我是用json获取图片的,不是直接从xml获取的
  • 显示你的 JSON 文件
  • [ { "product_name": "Flexible Hose Tangki Air Penguin", "product_image": "" }, { "product_name": "Foot Valve / Tusen Klep Tangki Air Penguin", "product_image": "" }, { "product_name": "Gasket Aksesoris Tangki Air Penguin", "product_image": "" } ]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多