如何更改 findViewById 以查看绑定?
Posted
技术标签:
【中文标题】如何更改 findViewById 以查看绑定?【英文标题】:How can i change findViewById to view binding? 【发布时间】:2021-08-14 20:16:29 【问题描述】:这是我的适配器代码;
class ModelViewHolder(view: View) : RecyclerView.ViewHolder(view)
private val chName: TextView = view.findViewById(R.id.chName)
private val chBirthYear: TextView = view.findViewById(R.id.chBirthYear)
private val chHeight: TextView = view.findViewById(R.id.chHeight)
private val chHomeWorld: TextView = view.findViewById(R.id.chHomeWorld)
【问题讨论】:
你能发布你的完整适配器代码吗? 【参考方案1】:获取列表项视图绑定类并如下更改:
//ItemModelBinding is the generated binding class for the list view item
class ModelViewHolder(val binding: ItemModelBinding) : RecyclerView.ViewHolder(binding.root)
fun bind(item: SomeModelClass)
binding.chName = item.chName
binding.chBirthYear = item.chBirthYear
binding.chHeight = item.chHeight
binding.chHomeWorld= item.chHomeWorld
binding.executePendingBindings()
override fun onBindViewHolder(holder: ModelViewHolder, position: Int)
val item = getItem(position)
holder.bind(item)
【讨论】:
【参考方案2】:class ModelViewHolder(view: View) RecyclerView.ViewHolder(view)
val binding = LayoutYouWantToUseBinding.bind(view)
【讨论】:
ViewHolder 必须是 ViewHolder 的子类。你会将什么视图传递给这个构造函数? 希望提供更多解释,但问题是“这是我的代码,我怎样才能将其更改为查看绑定”我认为这只是随机噪音,因为我认为我的答案中的代码几乎就是这个问题的答案。【参考方案3】:ListAdapter 是 RecyclerView.Adapter 基类,用于在 RecyclerView 中呈现 List 数据,包括在 后台线程上计算 List 之间的差异。
DiffUtil 有助于计算后台线程上两个列表之间的差异。并且仅更新已更改数据的视图意味着更少的 onBindViewHolder() 调用次数,如果我们仍然坚持使用 notifyDataSetChanged(),这将调用所有项目任何数据更改。
class ModelAdapter : ListAdapter<Model, ModelAdapter.ModelViewHolder>(ModelDiffCallBack())
class ModelViewHolder(private val binding: ModelItemLayoutBinding) :
RecyclerView.ViewHolder(binding.root)
fun bind(model: Model)
//if data binding is also enabled
binding.model = model
//else set data for each view one after another
binding.txtTitle.text = model.title
//and so on for all the items
binding.executePendingBindings()
companion object
fun from(parent: ViewGroup): ModelViewHolder
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ModelItemLayoutBinding.inflate(layoutInflater, parent, false)
return ModelViewHolder(binding)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModelViewHolder =
ModelViewHolder.from(parent)
override fun onBindViewHolder(holder: ModelViewHolder, position: Int)
val model = getItem(position)
holder.bind(model)
class ModelDiffCallBack : DiffUtil.ItemCallback<Model>()
override fun areItemsTheSame(oldItem: Model, newItem: Model): Boolean =
oldItem === newItem
override fun areContentsTheSame(oldItem: Model, newItem: Model): Boolean =
oldItem == newItem
【讨论】:
以上是关于如何更改 findViewById 以查看绑定?的主要内容,如果未能解决你的问题,请参考以下文章
在更改第一个 ddl 时使用 jquery ajax 绑定下拉列表
DataBinding快速入门(还在用findViewById?)
Angular JS 与 Laravel - 如何绑定 Eloquent ORM 数组以查看
Kotlin Android 视图绑定:findViewById vs Butterknife vs Kotlin Android Extension