Last active
January 17, 2020 02:51
-
-
Save yshrsmz/941c73e1edd12bba885cfff9555ca92e to your computer and use it in GitHub Desktop.
ViewBinding sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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