0

I am making a basic clicker game. For this who are not femuler: (Evertime the button is clicked it adds 1 to the value of the textView) which starts at 0 of course. This is what I have but there is an error at "as" which says this cast will never succeed(crushing my dreams)

fun click(v: View){
      textView.text as Int + 1
}

2 Answers2

0

Oh yeah. It won't work because textView.text is a CharSequence, which will never be able to cast to Int. This gets even more tricky because you can't treat a CharSequence as if it's a String. What you need to do is convert the text to a String, parse the current number in the textView, convert it into an Int and then re-add it back to the textView object.

Something like this:

fun click(v: View){
    val currentText = textView.text.toString()

    //Make sure that this will always be a number or you'll get an exception!
    val currentNumber = currentText.toInt()
    textView.text = currentNumber.plus(1).toString()
}

You can also do it all in one line but the above is much cleaner:

textView.text = textView.text.toString().toInt().plus(1).toString()
user2759839
  • 305
  • 1
  • 3
  • 11
0

The compiler is telling you that it is impossible to cast a the text (CharSequence) to an Int as mentioned by user2759839

But getting beyond the simple syntax error, you should not have to read from the textView at all. In general view objects should not hold state. They should capture user input or display info.

What you should do is create a private variable to hold the click count state, update that and then just use the TextView to display the value.

so something like this.

private var clickCount = 0

fun click(v: View) {
      clickCount += 1
      textView.text = "$clickCount"
}

This has the added benefit that you don't have to worry about the exception that can be thrown if the toInt() were to fail.

nPn
  • 16,254
  • 9
  • 35
  • 58