androidbroadcast / ViewBindingPropertyDelegate

Make work with Android View Binding simpler
https://proandroiddev.com/make-android-view-binding-great-with-kotlin-b71dd9c87719
Apache License 2.0
1.42k stars 102 forks source link

How to pass generic type to viewBindingDelegate #20

Closed Berki2021 closed 3 years ago

Berki2021 commented 3 years ago

I am trying to pass a generic type to the viewBinding Delegate, but it says: Cannot use 'vb' as reified type parameter. Use a class instead. Is this even possible?

abstract class BaseEmailFragment<out vb: ViewDataBinding>(
    layout: Int,
) : Fragment(layout) {

    private val binding by viewBinding<vb>() // Cannot use 'vb' as reified type parameter. Use a class instead.
}
kirich1409 commented 3 years ago

viewBinding() requires to know exactly class of ViewBinding. I’ll make this improvements in next release

kirich1409 commented 3 years ago

You need instance of Class if ViewBinding

Berki2021 commented 3 years ago

Hmm okay, thank you for the fast reply! Is it possible to say, when the next release will be published? I am looking forward for this feature 👍

kirich1409 commented 3 years ago

No. Right now you can do the next:


abstract class BaseEmailFragment<VB: ViewDataBinding>(
    layout: Int,
    vbClass: Class<VB>
) : Fragment(layout) {

    private val binding: VB by viewBinding(FragmentViewBinder(VB::class.java)::bind)
}

class FragmentViewBinder<T : ViewBinding>(private val viewBindingClass: Class<T>) {

    private companion object {
        val bindViewMethod by lazy(LazyThreadSafetyMode.NONE) {
            viewBindingClass.getMethod("bind", View::class.java)
        }
    }

    fun bind(fragment: Fragment): T {
        return bindViewMethod(null, fragment.requireView()) as T
    }
}
Berki2021 commented 3 years ago

Thanks I will try it out. But viewBindingClass.getMethod() did not work when using it in combination with private companion object. And in by viewBinding(FragmentViewBinder(VB::class.java)::bind) it still says "Cannot use 'vb' as reified type parameter. Use a class instead"

kirich1409 commented 3 years ago

Will be added in 1.3.0