Android RecyclerView 项目的双向数据绑定
Android Two-way Data-binding for RecyclerView Items
将模型的数据单向绑定到 recyclerview 项目很容易,因为我们向项目提供信息,但在某些情况下,我们需要从项目中获取数据(而不是事件),例如将人员列表作为项目,并为这些家伙的每个人输入 phone 编号。为此,我需要双向绑定项目的 phone 数据,但适配器中没有 lifecycleOwner。
inner class DataBindingViewHolder(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: T) {
binding.apply {
setVariable(BR.item, item)
executePendingBindings()
}
}
}
没有触发观察者的onChange()。这是因为 binding.apply {} 中没有设置 lifecycleOwner 并且传递片段的所有者会导致崩溃。
我已经通过在 BaseAdapter
的 DataBindingViewHolder
中实施 LifecycleOwner
来做到这一点。但是那里可能存在生命周期错误。所以请谨慎使用,我接受关于此实现的任何注释:
inner class DataBindingViewHolder(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root), LifecycleOwner {
private val lifecycleRegistry = LifecycleRegistry(this)
init {
lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED
}
fun onAppear() {
lifecycleRegistry.currentState = Lifecycle.State.CREATED
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
fun onDisappear() {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
fun bind(item: T) {
binding.apply {
lifecycleOwner = this@DataBindingViewHolder
setVariable(BR.item, item)
executePendingBindings()
root.apply {
setOnClickListener {
onItemClicked?.invoke(item, this)
}
setOnLongClickListener {
onItemLongClicked?.invoke(item, this)
return@setOnLongClickListener true
}
}
}
}
}
将模型的数据单向绑定到 recyclerview 项目很容易,因为我们向项目提供信息,但在某些情况下,我们需要从项目中获取数据(而不是事件),例如将人员列表作为项目,并为这些家伙的每个人输入 phone 编号。为此,我需要双向绑定项目的 phone 数据,但适配器中没有 lifecycleOwner。
inner class DataBindingViewHolder(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: T) {
binding.apply {
setVariable(BR.item, item)
executePendingBindings()
}
}
}
没有触发观察者的onChange()。这是因为 binding.apply {} 中没有设置 lifecycleOwner 并且传递片段的所有者会导致崩溃。
我已经通过在 BaseAdapter
的 DataBindingViewHolder
中实施 LifecycleOwner
来做到这一点。但是那里可能存在生命周期错误。所以请谨慎使用,我接受关于此实现的任何注释:
inner class DataBindingViewHolder(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root), LifecycleOwner {
private val lifecycleRegistry = LifecycleRegistry(this)
init {
lifecycleRegistry.currentState = Lifecycle.State.INITIALIZED
}
fun onAppear() {
lifecycleRegistry.currentState = Lifecycle.State.CREATED
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
fun onDisappear() {
lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
fun bind(item: T) {
binding.apply {
lifecycleOwner = this@DataBindingViewHolder
setVariable(BR.item, item)
executePendingBindings()
root.apply {
setOnClickListener {
onItemClicked?.invoke(item, this)
}
setOnLongClickListener {
onItemLongClicked?.invoke(item, this)
return@setOnLongClickListener true
}
}
}
}
}