Skip to content

Instantly share code, notes, and snippets.

@dancing-koala
Last active August 9, 2021 01:07
Show Gist options
  • Select an option

  • Save dancing-koala/55c9057c9c58930b6fc67cadc457d56f to your computer and use it in GitHub Desktop.

Select an option

Save dancing-koala/55c9057c9c58930b6fc67cadc457d56f to your computer and use it in GitHub Desktop.
Reduce boilerplate for view binding in fragments
// Just for customizing the name
// This alias makes the code more readable
typealias BindingInflater<VB> = (inflater: LayoutInflater, container: ViewGroup?, attachToRoot: Boolean) -> VB
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
// This property must be nullable to prevent view leaks
// Never forget that fragments outlive their views !
private var mutableViewBinding: VB? = null
// This property gives us a not nullable view binding for simpler use
protected val viewBinding: VB get() = mutableViewBinding!!
// This property is abstract because it has to be declared by the child class
protected abstract val bindingInflater: BindingInflater<VB>
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
mutableViewBinding = bindingInflater.invoke(inflater, container, false)
return viewBinding.root
}
override fun onDestroyView() {
super.onDestroyView()
// Prevent view leaks
mutableViewBinding = null
}
}
android {
...
// Enable view binding for module
buildFeatures {
viewBinding true
}
...
}
class ExampleFragment : BaseFragment<FragmentExampleBinding>() {
// FragmentExampleBinding.inflate(...) matches the signature of BindingInflater so we can
// set it as a BindingInflater for the FragmentExampleBinding class
override val bindingInflater: BindingInflater<FragmentExampleBinding> = FragmentExampleBinding::inflate
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(viewBinding) {
// Set up your views
...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment