[FIXED] How to output/print value to TextView

Issue

How to output/print value to TextView correctly?

TextView XML:

 <TextView
    android:id="@+id/playerOneScore"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

function:

var PlayerOneScore=12
var score: TextView = findViewById(R.id.playerOneScore) as TextView
score.setText(PlayerOneScore)

Solution

The signature of TextView.setText is compatible either with int (for android strings) or a CharSequence for normal or formatted strings. In your case, you are assigning an Int then the first signature is called.

To avoid this, you have to cast the value to String to show the value 12 in the textView. This can be achieved as follow:

myTextView.setText(myIntValue.toString())

take into consideration kotlin provide property access syntax to getText()/setText(). Using it you can avoid doing the same mistake.

myTextView.text = myIntValue //an error will be displayed because int isn't assignable for CharSequence
myTextView.text = myIntValue.toString() // Good !

In your case:

score.text = PlayerOneScore.toString()

Answered By – crgarridos

Answer Checked By – Marilyn (FixeMe Volunteer)

Leave a Reply

Your email address will not be published.