Skip to content

Instantly share code, notes, and snippets.

@makorowy
Last active November 22, 2020 14:53
Show Gist options
  • Save makorowy/82a8b49418f4aa1ae46e3591768aa62d to your computer and use it in GitHub Desktop.
Save makorowy/82a8b49418f4aa1ae46e3591768aa62d to your computer and use it in GitHub Desktop.
[BLOG] Example of common fragment implementation
class SettingsFragment : Fragment() {
private val viewModel: SettingsViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setInteractions()
observeViewModel()
}
private fun setInteractions() {
notificationsSwitch.setOnCheckedChangeListener { checked ->
viewModel.notificationsSwitchChanged(checked)
}
notificationsButton.setOnClickListener {
viewModel.notificationsSettingsButtonClicked()
}
/* other interactions */
}
private fun observeViewModel() {
viewModel.firstName.observe(viewLifecycleOwner, { firstName ->
firstNameText.text = firstName
})
viewModel.lastName.observe(viewLifecycleOwner, { lastName ->
lastNameText.text = lastName
})
viewModel.notificationEnabled.observe(viewLifecycleOwner, { checked ->
notificationsSwitch.isChecked = checked
notificationsButton.isEnabled = checked
})
/* other observers */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment