Day67 of #100DaysOfCode
Hii folks 🙌
Today I will be continuing the same pathway in which we’ll implement the OnClickListner for Submit Button.
Unit 3: Navigation
Pathway 2: Architecture componentsSource
https://developer.android.com/courses/android-basics-kotlin/course
Today we are going to implement the game logic for the Submit button click listener using the ViewModel
and the alert dialog.
- Now we will write the code to display the scrambled words:
private fun onSubmitWord() {
if (viewModel.nextWord()) {
updateNextWordOnScreen()
} else {
showFinalScoreDialog()
}
}
- And now we will add a helper method to validate player words. Before doing so we will add a new private method called
increaseScore()
with no parameters and no return value.
private fun increaseScore() {
_score += SCORE_INCREASE
}
- Now in the
GameViewModel
we will add a helper method that will return a Boolean and takes a String, the player’s word, as a parameter.
fun isUserWordCorrect(playerWord: String): Boolean {
if (playerWord.equals(currentWord, true)) {
increaseScore()
return true
}
return false
}
Now we will try to update the text field and it will show errors in the text field
private fun setErrorTextField(error: Boolean) {
if (error) {
binding.textField.isErrorEnabled = true
binding.textField.error = getString(R.string.try_again)
} else {
binding.textField.isErrorEnabled = false
binding.textInputEditText.text = null
}
}
Then we will implement the method onSubmitWord()
. When a word is submitted, we will validate the user’s guess by checking against word.
- In
GameFragment,
at the beginning ofonSubmitWord()
, we will create aval
calledplayerWord
. And we will store the player's word in it, by extracting it from the text field in thebinding
variable.
private fun onSubmitWord() {
val playerWord = binding.textInputEditText.text.toString()
if (viewModel.isUserWordCorrect(playerWord)) {
setErrorTextField(false)
if (viewModel.nextWord()) {
updateNextWordOnScreen()
} else {
showFinalScoreDialog()
}
}
}
- If the user word is incorrect, we will show an error message in the text field. Add an
else
block to the aboveif
block, and callsetErrorTextField()
passing intrue
. We completedonSubmitWord()
method should look like this:
private fun onSubmitWord() {
val playerWord = binding.textInputEditText.text.toString() if (viewModel.isUserWordCorrect(playerWord)) {
setErrorTextField(false)
if (viewModel.nextWord()) {
updateNextWordOnScreen()
} else {
showFinalScoreDialog()
}
} else {
setErrorTextField(true)
}
}
That is all for Day67 ✅
Thanks for reading, See you tomorrow!
If you are reading my #100Days Journey, feel free to drop by ;)