【问题标题】:is there a way to get layout resource from ViewDataBinding instance?有没有办法从 ViewDataBinding 实例中获取布局资源?
【发布时间】:2021-01-15 07:43:54
【问题描述】:

我正在尝试使用数据绑定构建自定义 Recycler 视图适配器,我想知道是否可以从绑定对象获取布局资源 ID,而不是每次都传递布局资源 给构造函数

class BaseAdapter<dataType,binder:ViewDataBinding>(val data:ArrayList<dataType>,@LayoutRes val resource:Int,val onBind: (binder, dataType, Int) -> Unit]) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder {
    val v = DataBindingUtil.inflate<binder>(
        LayoutInflater.from(parent.context),
        resource,
        parent,
        false
    )
    return BaseHolder(v)
}

override fun onBindViewHolder(holder: BaseHolder, position: Int) {
    onBind(holder.binding, items[position], position)
}

}

在我的活动中,我会这样使用它

BaseAdapter<String,MatchItemBinding>(arrayListOf(""),R.layout.match_item)

但我希望做这样的事情:

BaseAdapter<String,MatchItemBinding>(arrayListOf(""), MatchItemBinding.SOMETHING_TO_GET_LAYOUT_LINKED_WITH_THIS_OBJECT)

【问题讨论】:

  • ViewHolder 需要它吗? binder.root 在那里工作,例如RecyclerView.ViewHolder(binder.root)
  • 在初始化活页夹对象之前,我需要它用于 onCreateViewHolder:像这样 DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout............ ...,父母,假)
  • 您可以包含 ViewHolder 类的代码吗?包括 onCreateViewHolder
  • 完成,使用持有人代码更新问题

标签: android kotlin android-databinding


【解决方案1】:

这样的东西对你有用吗?

class BaseListAdapter<T, VDB : ViewDataBinding>(
    val data: ArrayList<T>,
    val onBind: (VDB, T, Int) -> Unit,
    val inflate: (layoutInflater: LayoutInflater, parent: ViewGroup?, attachToParent: Boolean) -> VDB
) : RecyclerView.Adapter<BaseListAdapter<T, VDB>.BaseHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseHolder =
        BaseHolder(inflate(LayoutInflater.from(parent.context), parent, false))

    inner class BaseHolder(val binding: VDB) : RecyclerView.ViewHolder(binding.root)
}

你可以像这样调用 inflate

{ li, parent, attachToParent -> SpecificDataBinding.inflate(li, parent, attachToParent) }

【讨论】:

  • 传递布局资源比这样做要简单得多:),我只是想知道是否有办法在不传递更多信息的情况下获取布局资源,因为我假设我的 ViewDataBinding 对象是相关的到唯一的布局资源
  • 公平 - binding.root.id 适合你吗?
猜你喜欢
  • 2017-04-07
  • 2015-10-18
  • 2011-07-31
  • 2017-10-04
  • 2019-04-22
  • 2017-06-10
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
相关资源
最近更新 更多