Skip to content

Instantly share code, notes, and snippets.

@pandulapeter
Created April 17, 2019 13:45
Show Gist options
  • Save pandulapeter/e25140922f9165720ab3d3c88dab299e to your computer and use it in GitHub Desktop.
Save pandulapeter/e25140922f9165720ab3d3c88dab299e to your computer and use it in GitHub Desktop.
abstract class BaseFragment<B : ViewDataBinding, VM : BaseViewModel>(@LayoutRes private val layoutResourceId: Int) : Fragment() {
private var realBinding: B? = null
protected val binding: B get() = realBinding ?: throw IllegalStateException("Trying to access the binding outside of the view lifecycle.")
protected abstract val viewModel: VM
final override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
DataBindingUtil.inflate<B>(inflater, layoutResourceId, container, false).also {
realBinding = it
}.root
@CallSuper
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.lifecycleOwner = viewLifecycleOwner
binding.setVariable(BR.viewModel, viewModel)
}
override fun onDestroyView() {
super.onDestroyView()
realBinding = null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment