如何动态地从多个TextView中更改文本?
我需要使用for循环设置已经存在于布局中的一些textView的文本.例如. TextView_01,TextView_02等.是否可以执行类似下面的推测性代码的方法:
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
}
这不是最好的处理方式,但它可能是最通用的,同时避免了创建预定义的TextViews数组:
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
}
由于您的语法错误,我对您的for循环进行了一些更改.我还用until
替换了..
,因为..
表示 through 是右边界,这可能不是您想要的.如果确实需要6
作为i
的值,则将其更改回..
.
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 ..
.
如果所有TextView都位于XML的单个父项下,请给该父项提供一个ID,然后遍历其子项:
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
}