将 myAdapter 合成转换为视图绑定
Posted
技术标签:
【中文标题】将 myAdapter 合成转换为视图绑定【英文标题】:convert myAdapter synthetic to viewbinding 【发布时间】:2022-01-12 09:01:52 【问题描述】:我很困惑,如何将我的适配器视图从合成更新为视图绑定! 这是我的代码,如何定义 viewbinding 到 viewHolder?
class PlayersListAdapter(
var items: ArrayList<MatchPlayer>
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder
val inflate: View =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_team_player, parent, false)
return MatchSubstitutionHolder(inflate)
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int)
viewHolder.itemView.lblPlayerName.text = "name"
class MatchSubstitutionHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
var view = itemView
override fun getItemCount(): Int
return items.size
【问题讨论】:
【参考方案1】:就像在片段或活动中定义视图绑定一样简单
class PlayersListAdapter(
var items: ArrayList<MatchPlayer>
) :
RecyclerView.Adapter<TeamPlayersListAdapter.MatchSubstitutionHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchSubstitutionHolder
val binding= ItemTeamPlayerBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return MatchSubstitutionHolder(binding)
override fun onBindViewHolder(viewHolder: MatchSubstitutionHolder, position: Int)
viewHolder.binding.lblPlayerName.text = "name"
class MatchSubstitutionHolder(val binding: ItemTeamPlayerBinding) : RecyclerView.ViewHolder(binding.root)
override fun getItemCount(): Int
return items.size
【讨论】:
【参考方案2】:我认为这是最适合你的
class PlayersListAdapter(var items: ArrayList<MatchPlayer>) :
RecyclerView.Adapter<TeamPlayersListAdapter.MatchSubstitutionHolder>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MatchSubstitutionHolder
val binding = ItemTeamPlayerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MatchSubstitutionHolder(binding)
override fun getItemCount(): Int
return items.size
override fun onBindViewHolder(viewHolder: MatchSubstitutionHolder, position: Int)
viewHolder.bind(position)
class MatchSubstitutionHolder(val binding: ItemTeamPlayerBinding) : RecyclerView.ViewHolder(binding.root)
fun bind(position: Int)
val matchPlayer = items[position]
binding.lblPlayerName.text = "name"
【讨论】:
以上是关于将 myAdapter 合成转换为视图绑定的主要内容,如果未能解决你的问题,请参考以下文章
如何让视图绑定与 RecyclerView.ViewHolder 中的 XML 布局高度一起使用,就像他们对 Kotlin Synthetics 所做的那样?