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

Generic Type to viewBinding() #83

Closed DatL4g closed 2 years ago

DatL4g commented 2 years ago

This issue reffers to #20 It's actually the same issue, but I wanted to open a new one instead of commenting on the old and closed.

I tried it like this

class Test<VB : ViewBinding> : Fragment() {
    val binding: VB by viewBinding()
}

However it cannot be called like that because of Cannot use VB as reified type parameter. Use a class instead. Additional I tried to call it like in your comment on the old thread https://github.com/androidbroadcast/ViewBindingPropertyDelegate/issues/20#issuecomment-712452508 but thats not possible either.

Is there any progress or workaround for this?

kirich1409 commented 2 years ago

You can use

class GenericFragment<VB : ViewBinding>(
    viewBindingClass: Class<VB>
) : Fragment() {

    private val viewBinding: VB by viewBinding(viewBindingClass)
}
DatL4g commented 2 years ago

@kirich1409 Sorry but that isn't practicable. In modern projects we don't create the Fragment ourself, instead this is done with NavigationComponents for example. So we cannot pass something in the Fragment's constructor easily.

Additionally having custom fragment constructors is a bad practice. Fragments need the default constructor. This is even descripted when you call a fragment with a custom constructor Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead and can even result in a crash when it tries to recreate the fragment.

kirich1409 commented 2 years ago

The proposed class will be used as base class

abstract class VBFragment<VB : ViewBinding>(
    viewBindingClass: Class<VB>
) : Fragment() {

    protected val viewBinding: VB by viewBinding(viewBindingClass)
}
class MyFragment() : VBFragment<MyViewBinding>(MyViewBinding::class.java)
kirich1409 commented 2 years ago

It's not possible to create instance without understanding type of VB. It can be set via Class instance or extracting using reified, but in your case this is impossible