在Kotlin中使用HashMap迭代键值对并在RecyclerView中显示可以按以下步骤进行:
val hashMap = HashMap<String, String>()
hashMap["key1"] = "value1"
hashMap["key2"] = "value2"
hashMap["key3"] = "value3"
data class KeyValue(val key: String, val value: String)
class KeyValueAdapter(private val data: List<KeyValue>) : RecyclerView.Adapter<KeyValueAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_key_value, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val keyValue = data[position]
holder.bind(keyValue)
}
override fun getItemCount(): Int {
return data.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(keyValue: KeyValue) {
itemView.keyTextView.text = keyValue.key
itemView.valueTextView.text = keyValue.value
}
}
}
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val hashMap = HashMap<String, String>()
hashMap["key1"] = "value1"
hashMap["key2"] = "value2"
hashMap["key3"] = "value3"
val keyValueList = ArrayList<KeyValue>()
for ((key, value) in hashMap) {
keyValueList.add(KeyValue(key, value))
}
val adapter = KeyValueAdapter(keyValueList)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
这样,HashMap中的键值对数据将会在RecyclerView中显示出来。你可以根据实际情况修改适配器和布局文件来满足你的需求。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云