使用RecyclerView视图适配器在xml中添加两个ViewModel类的步骤如下:
implementation 'androidx.recyclerview:recyclerview:1.2.1'
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
class ItemViewModel {
private var title: String? = null
private var description: String? = null
fun getTitle(): String? {
return title
}
fun setTitle(title: String) {
this.title = title
}
fun getDescription(): String? {
return description
}
fun setDescription(description: String) {
this.description = description
}
}
class MyAdapter(private val itemList: List<ItemViewModel>) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = itemList[position]
holder.titleTextView.text = item.getTitle()
holder.descriptionTextView.text = item.getDescription()
}
override fun getItemCount(): Int {
return itemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleTextView: TextView = itemView.findViewById(R.id.titleTextView)
val descriptionTextView: TextView = itemView.findViewById(R.id.descriptionTextView)
}
}
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
// 创建一个包含数据的ViewModel列表
val itemList: List<ItemViewModel> = listOf(
ItemViewModel().apply {
setTitle("项目1")
setDescription("这是项目1的描述")
},
ItemViewModel().apply {
setTitle("项目2")
setDescription("这是项目2的描述")
}
)
// 创建适配器并设置给RecyclerView
val adapter = MyAdapter(itemList)
recyclerView.adapter = adapter
// 创建并设置布局管理器
recyclerView.layoutManager = LinearLayoutManager(this)
这样,你就可以在xml中使用RecyclerView视图适配器,并在两个ViewModel类中设置数据以供显示。请根据实际需求进行适当修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云