You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建TextView数组/列表,通过索引动态设置其.text属性?

解决方案:批量管理TextView并循环设置文本

一、先正确初始化TextView集合

根据你的场景,分两种常见情况处理:

情况1:XML布局中已定义多个TextView

如果布局里已有多个TextView(比如id为tv_0到tv_19),可以用以下方式批量存入列表:

// 推荐用ViewBinding(替代findViewById)
val textViews = listOf(
    binding.tv0, binding.tv1, binding.tv2, ..., binding.tv19
)

// 未使用ViewBinding时,用findViewById批量获取:
val textViews = mutableListOf<TextView>()
repeat(20) { index ->
    val tvId = resources.getIdentifier("tv_$index", "id", packageName)
    val tv = findViewById<TextView>(tvId)
    textViews.add(tv)
}

情况2:动态创建TextView并添加到布局

如果需要动态生成TextView,直接在代码中创建并加入集合:

val container = findViewById<LinearLayout>(R.id.container) // 布局中的容器控件
val textViews = mutableListOf<TextView>()

repeat(20) {
    val tv = TextView(this).apply {
        layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        // 可按需设置字体、内边距等属性
    }
    container.addView(tv)
    textViews.add(tv)
}

二、修正你的循环逻辑

原代码存在几个关键问题:

  • userID初始仅含一个空字符串,索引越界会报错
  • 内层while循环中,当tweetStored[token]为false时,token不递增,会陷入无限循环
  • textView集合未初始化,直接调用会触发空指针异常

以下是修正后的完整逻辑:

var refillToken = 5.0 // 替换为你的实际token数值
val tweetStored = BooleanArray(20).apply {
    // 模拟部分位置为true的场景,可替换为你的实际数据
    this[0] = true
    this[2] = true
    this[3] = true
    this[5] = true
    this[7] = true
}
val tweetActive = BooleanArray(20)
// 初始化userID,确保长度与tweetStored一致
val userID = List(20) { index -> "User_$index" }
// 已通过上面的步骤初始化好textViews集合
var textViewToken = 0

// 改用for循环避免无限循环问题
for (token in tweetStored.indices) {
    if (refillToken <= 0) break
    if (tweetStored[token]) {
        tweetActive[token] = true
        // 确保不超出TextView集合的范围
        if (textViewToken < textViews.size) {
            textViews[textViewToken].text = userID[token]
            textViewToken++
            refillToken--
        }
    }
}

三、更简洁的Kotlin风格写法

利用Kotlin的集合操作简化代码:

// 筛选出符合条件的userID,且不超过refillToken数量
val validUserIds = tweetStored.indices
    .filter { tweetStored[it] }
    .take(refillToken.toInt())
    .map { userID[it] }

// 批量设置TextView文本
validUserIds.forEachIndexed { index, userId ->
    if (index < textViews.size) {
        textViews[index].text = userId
        // 同步更新tweetActive状态
        tweetStored.indices.first { tweetStored[it] && userID[it] == userId }.let {
            tweetActive[it] = true
        }
    }
}

内容的提问来源于stack exchange,提问作者Nicholas Klein-Boonschate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:18:21