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 cannot be used #117

Closed merlinJeyakumar closed 1 year ago

merlinJeyakumar commented 1 year ago

How to use generic type

abstract class BaseActivity<B : ViewDataBinding, VM : BaseViewModel>( private val bindingFactory: Int, private val viewModelClass: Class, ) : AppCompatActivity() {

protected val binding: B by viewBinding()

}

kirich1409 commented 1 year ago

It's not possible. To create an instance the delegate needs to now ViewBinding class.

kirich1409 commented 1 year ago

The delegate few creation variants and one of them has ViewModel class as parameter or even you can pass function where you will create an instance of ViewBinding

kirich1409 commented 1 year ago

https://github.com/androidbroadcast/ViewBindingPropertyDelegate/blob/master/vbpd/vbpd-full/src/main/java/by/kirich1409/viewbindingdelegate/ActivityViewBindings.kt 37 line

merlinJeyakumar commented 1 year ago
    @LayoutRes private val layoutRes: Int,
) {

    private var binding: T? = null

    operator fun getValue(activity: R, property: KProperty<*>): T {
        if (binding == null) {
            binding = DataBindingUtil.setContentView<T>(activity, layoutRes).apply {
                lifecycleOwner = activity
            }
        }
        return binding!!
    }
}

fun <R : AppCompatActivity, T : ViewDataBinding> contentView(
    @LayoutRes layoutRes: Int,
): ContentViewBindingDelegate<R, T> = ContentViewBindingDelegate(layoutRes)

I have created and using this extension function, while using it with navigation view it causing crash NavHost.context() null pointer

merlinJeyakumar commented 1 year ago

its working fine for my baseclass,

you can close this ticket, Problem is I called lifecycle binding before activity creation