Skip to content

Instantly share code, notes, and snippets.

@riggaroo
Last active February 3, 2019 10:15
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 riggaroo/ea3bcc9e0d4b891dfc1dc43711e31e7b to your computer and use it in GitHub Desktop.
Save riggaroo/ea3bcc9e0d4b891dfc1dc43711e31e7b to your computer and use it in GitHub Desktop.
ProjectEditorFragment showing how to use ViewModels to restore state.
class ProjectEditorFragment : Fragment {
@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: ProjectEditorViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_editor_initial, container, false)
AndroidSupportInjection.inject(this)
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(requireActivity(), viewModelFactory)
.get(ProjectEditorViewModel::class.java)
setupViewModel()
}
private fun setupViewModel() {
viewModel.state.observe(this, Observer { editorState ->
editorState?.let { state ->
// Set the state of all controls based on the saved state in the ViewModel
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment