How to set x and y values of TextView in Android Studio Programmatically

Viewed 60

I am trying to set a random value for textview of x and y together in 1 forloop.

I have a function

fun createTextView(text: String, index: Int): TextView

and on another function, I am using a for loop to create the TextView based on number of words in a list.

       val words = arrayListOf("abc","def","ghi")

       for ((wordIndex, i) in words.withIndex()){
            createTextView(i,wordIndex).x = some random number
        }

From this loop, I can only set either x or y value for my textview. How do I make it such that I can set both x and y value inside my for loop?

1 Answers

You can just store the return value in a variable and do it like this.

   val words = arrayListOf("abc","def","ghi")

   for ((wordIndex, i) in words.withIndex()){
      val textView = createTextView(i, wordIndex)
      textView.x = some random number
      textView.y = some random number
    }
Related