Home > Mobile >  How do/ can I print an arrays contents into a textView in Android Studios Kotlin
How do/ can I print an arrays contents into a textView in Android Studios Kotlin

Time:09-17

lets say I'm making a simple dnd dice roller (cause I am), I get results and I turn it into an array. Now I want to print the results of the array into a textView that would say: randNumResultsDisplay.text = "Rolled " then it would spit out all results in the array, in order that they were put in.

CodePudding user response:

I'm not entirely sure where you are stuck here, but if you want to convert an array into a String, one option is to use the java.utils.Arrays class:

val myArray = arrayOf(1, 2, 3)
val contents = Arrays.toString(myArray)
println(contents) // prints "[1, 2, 3]"

So to inject that in your text view as you suggested:

randNumResultsDisplay.text = "Rolled ${Arrays.toString(yourValuesArray)}"

That being said, you would get it for free if you used List instead of Array (which is very much advised):

randNumResultsDisplay.text = "Rolled $yourList"

Another option as pointed out in the comments is the joinToString method, which works on both arrays and lists and allows you to customize the formatting:

println("Rolled: ${myArray.joinToString()}")
// Rolled 1, 2, 3

println("Rolled: ${myArray.joinToString(prefix = "[", postfix = "]")}")
// Rolled [1, 2, 3]

println("Rolled: ${myArray.joinToString(separator = "|")}")
// Rolled 1|2|3
  • Related