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

Crash in DialogFragment. ID does not reference a View inside this View #55

Open SwiftyWang opened 3 years ago

SwiftyWang commented 3 years ago

I am using this library 1.4.5 version. With this function public inline fun <F : Fragment, T : ViewBinding> Fragment.viewBinding( crossinline vbFactory: (View) -> T, @IdRes viewBindingRootId: Int ) And working in activity and fragment. When using in DialogFragment. The app crash when I try to use viewBinding instance in onViewCreated callback. After some investigated, found the dialog contentView will be set in onActivityCreated which is called after onViewCreated. But the delegate will get the view from dialog inside.

Is that a bug? Please give some suggestions, thanks.

kirich1409 commented 3 years ago

Hi. I need to see code of the Fragment where you have the issue

kirich1409 commented 3 years ago

And stacktrace when crash occured

SwiftyWang commented 3 years ago

Normally we use DialogFragment like using a normal fragment. We create view in onCreateView and use views in onViewCreated (or onCreateView). When use Fragment.viewBinding with viewBindingRootId . It will throw exception in Utils L46. Seems view hasn't added into dialog window. I checked androidx DialogFragment source code. It add view to dialog in onActivityCreated which after onCreateView and onViewCreated.

Now I am using viewBinding function without given rootViewId seems working.

After reading some source code, seems without given rootViewId, The lib will binding view from Fragment::requireView but with given rootViewId it will try to find view from dialog window. Internal logics in these two methods are different.

outofdate commented 3 years ago

Yeah, we got the same issue, as we are accessing bindings in onViewCreated. After some digging we find out the same reason - dialog window view is without our view, as it is added in onActivityCreated of DialogFragment.

nzeeei commented 3 years ago

Is there any reason why the author is finding the view in dialog view, not fragment view? Have the same issue

kirich1409 commented 3 years ago

DialogFragment can be used as usual Fragment that will be added as View in layout or can be shown as Dialog. A ViewBinding require a View. I will think how it can be done better. Right now DialogFragment implementation isn't good a don't work everywhere. Let's discuss how to do that better

rantianhua commented 3 years ago

@kirich1409 Maybe this way is better:

    val view = dialog?.findViewById<View>(viewBindingRootId)
    if (view != null) {
        return view
    }
    return requireView().requireViewByIdCompat(viewBindingRootId)

Find the view from the dialog at first, then find it from the fragment view.