<@UJBKXD0HH> <@U3JQ35YQK> why didn’t the Android U...
# android
k
@Adam Powell @romainguy why didn’t the Android UI team make View Binding to be as simple as kotlin synthetics where one can just access the view in code by just specifying the view ID alone instead of writing this boilerplate required in 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() {
    super.onDestroyView()
    _binding = null
}
j
you can create your viewbinding delegate
usage:
private val binding by viewBinding(MyFragmentBinding::bind)
k
Thanks @Javier I will look into that
s
I have created a root Fragment as following:
Copy code
abstract class MyFragment<B : ViewBinding>(private val binder: (LayoutInflater) -> B) : Fragment() {
    
    private var _binding: B? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    protected val binding get() = _binding!!

    final override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = binder(inflater)
        return binding.root
    }
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
and usage is:
Copy code
class ChildFragmentFragment : MyFragment<FragmentChildBinding>( FragmentChildBinding::inflate) {
    fun method(){
        binding.text1.text = "Hello World"
    }
}
😐 1
j
I would avoid inheritance if a delegate could do the job
👍 5
s
Yeah, it is matter of choice. I had already root fragment for other purposes, so… But I would double think if I knew about delegate solution back then. I liked it as well.
👍 2
k
Thanks
s
You also don't have to create a property for it: https://lordraydenmk.github.io/2020/view-binding/
☝️ 2
❤️ 1
f
a
s
@Javier I am trying to use lifecycle as you did for a different purpose, but I notice
onDestroy
is not called on fragment while
onDestroyView
is called when I have a viewPager to contain couple of fragments. Do you have an idea?
it causes a leak o/w.
it seems
onDestroy
on fragments when used in a viewPager is not trustworthy: https://stackoverflow.com/a/17195813 still digging. --- conversation on gist continued on this problem as well, I got it again.
z
i don't even know why you're trying to rely on
onDestroy
. That only happens if you navigate back from the fragment
s
I am trying to rely on
Copy code
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)