ViewBindingPropertyDelegate icon indicating copy to clipboard operation
ViewBindingPropertyDelegate copied to clipboard

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

Open SwiftyWang opened this issue 5 years ago • 7 comments

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.

SwiftyWang avatar Apr 09 '21 08:04 SwiftyWang

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

kirich1409 avatar Apr 11 '21 08:04 kirich1409

And stacktrace when crash occured

kirich1409 avatar Apr 11 '21 08:04 kirich1409

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.

SwiftyWang avatar Apr 12 '21 03:04 SwiftyWang

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.

outofdate avatar Apr 29 '21 11:04 outofdate

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

NZeee avatar Apr 29 '21 15:04 NZeee

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

kirich1409 avatar May 06 '21 08:05 kirich1409

@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.

rantianhua avatar May 17 '21 07:05 rantianhua