Last active
August 29, 2022 10:19
-
-
Save Skyyo/14ca91842699ef8545c8b136c159b727 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
enum class FocusedTextFieldKey { | |
NAME, CREDIT_CARD_NUMBER, NONE | |
} | |
@HiltViewModel | |
class InputValidationViewModel @Inject constructor(..) : ViewModel() { | |
private var focusedTextField = handle.get("focusedTextField") ?: FocusedTextFieldKey.NAME | |
set(value) { | |
field = value | |
handle.set("focusedTextField", value) | |
} | |
init { | |
if (focusedTextField != FocusedTextFieldKey.NONE) focusOnLastSelectedTextField() | |
} | |
fun onTextFieldFocusChanged(key: FocusedTextFieldKey, isFocused: Boolean) { | |
focusedTextField = if (isFocused) key else FocusedTextFieldKey.NONE | |
} | |
fun onNameImeActionClick() { | |
_events.trySend(ScreenEvent.MoveFocus(FocusDirection.Down)) | |
} | |
fun onContinueClick() { | |
viewModelScope.launch(Dispatchers.Default) { | |
if (areInputsValid.value) clearFocusAndHideKeyboard() | |
.. | |
} | |
} | |
private suspend fun clearFocusAndHideKeyboard() { | |
_events.send(ScreenEvent.ClearFocus) | |
_events.send(ScreenEvent.UpdateKeyboard(false)) | |
focusedTextField = FocusedTextFieldKey.NONE | |
} | |
private fun focusOnLastSelectedTextField() { | |
viewModelScope.launch(Dispatchers.Default) { | |
_events.send(ScreenEvent.RequestFocus(focusedTextField)) | |
delay(250) | |
_events.send(ScreenEvent.UpdateKeyboard(true)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment