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

为LinearLayout内TextView动态设监听器时无法访问text属性

解决LinearLayout中子TextView点击获取文本的问题

问题核心在于LinearLayout.children返回的是泛型View实例,而text是TextView的专属属性,直接通过it访问会因类型不匹配无法调用。

修复方案一:安全类型判断(推荐)

遍历子View时先判断是否为TextView类型,再设置点击监听,避免类型转换异常:

package com.jym.qb

class PrintActivity : AppCompatActivity() {

    private val vBinding by lazy { ActivityPrintBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(vBinding.root)

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

修复方案二:直接强转(适用于确定所有子View都是TextView的场景)

如果能保证optionLayout下仅包含TextView,可以直接强转类型:

for(item in vBinding.optionLayout.children){
    val textView = item as TextView
    textView.setOnClickListener{
        Log.d("test", textView.text.toString())
    }
}

额外提醒

布局中使用的tools:text仅用于Android Studio预览,运行时不会生效,需要替换为android:text才能在点击时获取真实文本:

<TextView
    android:id="@+id/option0"
    android:text="option0" />

<TextView
    android:id="@+id/option1"
    android:text="option1" />

<TextView
    android:id="@+id/option2"
    android:text="option2" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:15:48