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

Kotlin中循环获取动态添加的TextView文本报编译错误的解决方法

问题解决:Unresolved reference: text 编译错误

错误原因

vBinding.linearLayout.children 返回的是 Sequence<View> 类型的集合,而View 类并没有 text 属性——只有 TextView(及其子类)才具备该属性,因此直接访问 item.text 会触发编译错误。

解决方法

方法1:类型判断后访问

在循环中先校验当前子View是否为TextView,再安全访问其text属性:

vBinding.submitBtn.setOnClickListener {
    for(item in vBinding.linearLayout.children){
        if(item is TextView){
            Log.d("test", "${item.text}")
        }
    }
}

方法2:安全转换避免崩溃

使用 as? 进行安全类型转换,转换失败时返回null,配合空安全操作符处理:

vBinding.submitBtn.setOnClickListener {
    for(item in vBinding.linearLayout.children){
        val textView = item as? TextView
        textView?.let { tv ->
            Log.d("test", "${tv.text}")
        }
    }
}

方法3:直接过滤TextView类型子View

用 filterIsInstance<TextView>() 直接筛选出LinearLayout中所有TextView,循环时直接操作目标类型:

vBinding.submitBtn.setOnClickListener {
    vBinding.linearLayout.children.filterIsInstance<TextView>().forEach { tv ->
        Log.d("test", "${tv.text}")
    }
}

内容的提问来源于stack exchange,提问作者조영민

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:24:46