【发布时间】:2020-04-30 02:18:31
【问题描述】:
我在我的布局中使用数据绑定到 RecyclerView,如下所示:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/topup_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:items="@{viewModel.items}"
tools:listitem="@layout/list_item_content" />
以及列表和绑定适配器,例如:
@BindingAdapter("app:items")
fun setItems(listView: RecyclerView, items: List<ListItem>?) {
items?.let {
(listView.adapter as MyListAdapter).submitList(items)
}
}
//------------------
class MyListAdapter() :
ListAdapter<ListItem, ViewHolder>(myListItemDiffCallback()) {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
class ViewHolder private constructor(private val binding: ListItemContentBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: ListItem) {
binding.item = item
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = TopUpListItemContentBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
}
}
class myListItemDiffCallback : DiffUtil.ItemCallback<ListItem>() {
override fun areItemsTheSame(oldItem: ListItem, newItem: ListItem): Boolean {
return oldItem.label == newItem.label
}
override fun areContentsTheSame(
oldItem: ListItem,
newItem: ListItem
): Boolean {
return oldItem == newItem
}
}
但是使用简单的 ListView 就不一样了。出于多种原因,我更喜欢使用列表视图并且我尝试过,但我不知道如何像在 RecycleView 中使用的那样自定义我的适配器以进行数据记录。
下面是我的 Listview 适配器:
class MyListAdapter(context: Context, items: List<ListItem>) :
ArrayAdapter<ListItem>(context, 0, items) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val binding = ListItemContentBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
binding.item = getItem(position)
return binding.root
}
}
我的项目类模型:
data class ListItem(
val iconResId: Int,
val label: String,
val action: () -> Unit
)
有人知道吗?
【问题讨论】:
-
您可以为
ListView添加您的adapter吗? -
好的,我刚刚更新了我的代码..
标签: android data-binding android-listview android-databinding