Closed DatL4g closed 2 years ago
You can use
class GenericFragment<VB : ViewBinding>(
viewBindingClass: Class<VB>
) : Fragment() {
private val viewBinding: VB by viewBinding(viewBindingClass)
}
@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.
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)
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
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
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?