-1

I need to set the text of some textViews already existing in a layout with a for loop. Eg. TextView_01, TextView_02, etc. IS there a way to do something like the following speculative code:

for(1 in 0..6){
       TextView_0(change value with i).text = something
}

3 Answers3

1

This isn't the best way to do things, but it's probably the most universal, while avoiding creating a pre-defined array of TextViews:

val base = "TextView_0"

for (i in 1 until 6) {
    val textView = findViewById(resources.getIdentifier("${base}i", "id", packageName)
    textView.text = something
}

I changed your for loop a little bit, since you had the wrong syntax. I also replaced .. with until, since .. means through the right bound, which probably isn't what you want. If you do need 6 to be a value of i, then change it back to ...


If all the TextViews are under a single parent in XML, give that parent an ID, then loop through its children:

val parent = findViewById(R.id.tvParent)

for (i in 0 until parent.getChildCount()) {
    (container.getChildAt(i) as TextView).text = something
}
TheWanderer
  • 16,775
  • 6
  • 49
  • 63
  • Your first solution is what I had in mind, tried it but didn't properly work, somehow it was producing some null TextViews values. As stated by Tim, someone asked this before and yes, the way to deal with this is with an array. Thanks ayway, will look deeper in your dynamic syntax which is what I really wanted. – Ricardo Romero Ruiz Oct 19 '18 at 14:16
  • 1
    How many TextViews do you have? If it's returning null values it's because one of the IDs doesn't exist. Maybe `TextView_06` doesn't exist? Check your names. – TheWanderer Oct 19 '18 at 14:18
-1

You can use parent container

    for (i in 0 until container.childCount) {
        (container.getChildAt(i) as TextView).text = something
    }
Yonfu
  • 19
  • 2
-1

A better way is to make use of DataBinding and LiveData APIs, you can assign different variables or the same variable to your TextViews' text attributes.

Basil
  • 845
  • 9
  • 24