'Kotlin: return a value on button click
I'm just starting out on learning Kotlin, and I'm currently making a simple Quiz application for Android. The user can choose an answer with four buttons which are stored in an array. The program contains a functions which is supposed to check if the correct button is clicked and return a corresponding boolean:
fun checkAnswer (solution: Int): Boolean {
for (z in answerButtons.indices) {
answerButtons[z].setOnClickListener{
return z == solution
}
}
}
Now I know that this return
doesn't work, but I just can't find a way to return a value depending on which button is clicked. If anyone could help me here, I'd be very grateful. Thanks!
Solution 1:[1]
So when you call setOnClickListener
, the Kotlin compiler is really abstracting away some important details. What is really happening is this:
setOnClickListener(object: View.OnClickListener {
override fun onClick(v: View?) {
doAThing()
}
})
This is a SAM constructor. But, as you can see, the return type of onClick
is Unit, and it doesn't make sense to return from an anonymous object either. It would help to have more context as to why you've structured your code the way you have, but here's a potential solution to your problem:
// in onCreate
for (btn in answerButtons) {
btn.setOnClickListener {
if (btn.text == solution) {
doTheThingWhenCorrectAnswer()
} else {
doTheThingWhenIncorrectAnswer()
}
}
}
If this were a real application, I would additionally suggest pushing the logic for checking answers into the model layer to maintain strong separation of concerns.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | FutureShocked |