I'm trying to update/notify the adapter based on a value from the API call I get and I do have a DiffUtil callback in my adapter for the same. If I use viewBinding UI is not showing up but if I do use findViewById like this it seems to be working fine. Any help/leads appreciated. Thank you!
//ViewBinding ain't working along with DiffUtils for Some reason
(view?.findViewById(R.id.recyclerView) as RecyclerView).apply {
layoutManager = LinearLayoutManager(requireContext())
adapter = temListAdapter
}
updateAdapter()
with(binding) {
submitBtn.setOnClickListener(this@ALFragment)
cancelBtn.setOnClickListener(this@ALFragment)
header.headerText.setOnClickListener(this@ALFragment)
header.headerRightArrow.setOnClickListener(this@ALFragment)
}
This Is how I am binding in this current Fragment
private val binding by viewBinding(FragmentConfirmBinding::bind)
And this is the ViewBinding Util class for the fragments am using
class FragmentViewBinding<T : ViewBinding>(val fragment: Fragment, val viewBindingFactory: (View) -> T) : ReadOnlyProperty<Fragment, T> {
private var binding: T? = null
init {
// Note: There's an open issue of memory leaks with view binding in fragments
// Solution: Destroying binding on fragment destroy thus observing fragment's lifecycle to clear binding when fragment is destroyed
fragment.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
fragment.viewLifecycleOwnerLiveData.observe(fragment, {
it.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
// clear this binding value when the views are destroyed
binding = null
}
})
})
}
})
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T {
val bindingRef = binding
if (bindingRef != null) return bindingRef
val lifecycle = fragment.viewLifecycleOwner.lifecycle
if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) {
throw IllegalStateException(FRAGMENT_KILLED_EXCEPTION_TEXT)
}
return viewBindingFactory(thisRef.requireView()).also { binding = it }
}
companion object {
private const val FRAGMENT_KILLED_EXCEPTION_TEXT = "Should not attempt to get bindings when Fragment views are destroyed."
}
}
/**
* Extension method for fragment view binding
*/
fun <T : ViewBinding> Fragment.viewBinding(viewBindingFactory: (View) -> T) = FragmentViewBinding(this, viewBindingFactory)
question from:
https://stackoverflow.com/questions/65859889/viewbinding-in-recyclerview-along-with-diffutils-callback-isnt-working 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…