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

Kotlin中Type Argument越界错误解决及TextView文本赋值方法

Android TextView赋值报错的解决办法

问题描述

从另一个Activity获取字符串值:
val txt: String = intent.getStringExtra("resultval").toString()

布局中的TextView代码:

<TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id = "@+id/prNumberId"
      android:text = "PR Number"
      android:textColor="@color/black"
      android:textSize = "20sp"
      android:textStyle = "bold"/>

想要将TextView默认文本替换为类似PR7438927438927的内容,但使用以下代码时出现Type Argument is not within its bounds错误:
findViewById<Text>(R.id.prNumberId).replaceWholeText(txt)
findViewById<Text>(R.id.prNumberId).textContent = txt


解决方法

  • 错误根源:findViewById的泛型类型写错了,Android中的文本控件类是TextView,而非Text,类型不匹配导致报错。
  • 正确赋值方式:
    1. 先获取正确类型的TextView实例:
      val prNumberTv = findViewById<TextView>(R.id.prNumberId)
    2. 使用Android标准的text属性设置内容:
      prNumberTv.text = txt
  • 空安全优化:intent.getStringExtra("resultval")可能返回null,直接调用toString()会触发空指针异常,建议提前处理:
    val txt = intent.getStringExtra("resultval") ?: "默认PR编号"
    val prNumberTv = findViewById<TextView>(R.id.prNumberId)
    prNumberTv.text = txt
    

内容的提问来源于stack exchange,提问作者Milkova Fitzgerald

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:17:31