Skip to content

Instantly share code, notes, and snippets.

@yshrsmz
Last active January 17, 2020 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yshrsmz/941c73e1edd12bba885cfff9555ca92e to your computer and use it in GitHub Desktop.
Save yshrsmz/941c73e1edd12bba885cfff9555ca92e to your computer and use it in GitHub Desktop.
ViewBinding sample
class HomeFragment: Fragment(R.layout.fragment_home) {
private val binding by viewBinding { FragmentHomeBinding.bind(it) }
// do not implement onCreateView!
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.mainText.text = "Hello World!"
}
}
fun <VB : ViewBinding> Fragment.viewBinding(viewBindingFactory: (view: View) -> VB): ReadOnlyProperty<Fragment, VB> {
return object : ReadOnlyProperty<Fragment, VB> {
override fun getValue(thisRef: Fragment, property: KProperty<*>): VB {
val view = thisRef.view!!
@Suppress("UNCHECKED_CAST") var binding = view.getTag(R.id.viewbinding_tag) as? VB
if (binding == null) {
binding = viewBindingFactory(view)
view.setTag(R.id.viewbinding_tag, binding)
}
return binding
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment