Last active
November 22, 2020 14:53
-
-
Save makorowy/82a8b49418f4aa1ae46e3591768aa62d to your computer and use it in GitHub Desktop.
[BLOG] Example of common fragment implementation
This file contains 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 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