https://kotlinlang.org logo
#android
Title
# android
j

Javier

02/05/2020, 11:35 AM
From here: https://developer.android.com/topic/libraries/view-binding
Copy code
private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    _binding = null
}
binding
cannot be null never? If for some reason I want to get the context via
binding.root.context
and the fragment is not attached, I can not get a NPE? @jw
a

arekolek

02/05/2020, 11:46 AM
so if somebody else knows the answer, you're not interested? 😉
j

Javier

02/05/2020, 11:47 AM
@arekolek yes, I am interested, but I mentioned Jake because he was developing this feature
a

arekolek

02/05/2020, 11:47 AM
btw, this is related to kotlin how?
j

Javier

02/05/2020, 11:51 AM
About if it is safe to use
_binding!!
and Kotlin type safe feature is not being affected.
s

satyan

02/05/2020, 11:56 AM
If your fragment is not attached you’ll get a NPE.
_binding
is set to
null
onDestroyView
(which make sense since the binding is suppose to contains the view)
https://github.com/xxv/android-lifecycle (
onDetach
being after
onDestroyView
) In which use case would you need to get the attached context of your fragment after
onDetach
?
And if you store the context from your binding, in some cases, if the place your store it outlive the fragment’s attached context, you’re going to leak it.
j

Javier

02/05/2020, 12:45 PM
Really one reason I move from synthetics to data binding is because some times if you navigate so quickly between fragments you can get that your views are null, with databinding I didn't see I have to do this trick in
onDestroy
and the problem was resolved. Then I have doubts about if I can get the same problems I had with synthetics if I don't check if any view or view context is null with view binding
2 Views