Day67 of #100DaysOfCode

Kushagra Kesav
2 min readApr 14, 2022

--

#CodeTogether Day 67/100

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 of onSubmitWord(), we will create a val called playerWord. And we will store the player's word in it, by extracting it from the text field in the binding 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 above if block, and call setErrorTextField() passing in true. We completed onSubmitWord() 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 ;)

--

--