如何动态地从多个TextView中更改文本? [英] how can I change the text from several TextViews dynamically?

查看:207
本文介绍了如何动态地从多个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
}

这篇关于如何动态地从多个TextView中更改文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆