如何更改 findViewById 以查看绑定?

How can i change findViewById to view binding?

这是我的适配器代码;

    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)

获取列表项视图绑定 class 并将其更改为:

//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)
    }
class ModelViewHolder(view: View) RecyclerView.ViewHolder(view){
    val binding = LayoutYouWantToUseBinding.bind(view)
}

ListAdapter 是 RecyclerView.Adapter 基础 class,用于在 RecyclerView 中呈现列表数据,包括在 后台线程上计算列表之间的差异.

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
}

}