Created
April 17, 2019 13:45
-
-
Save pandulapeter/e25140922f9165720ab3d3c88dab299e to your computer and use it in GitHub Desktop.
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
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