在 Kotlin 中通过 ID 更改 XML 布局文本的值

问题描述 投票:0回答:1

我有一个来自其他活动的值,我想将其作为布局文本的新值:

val txt:String = intent.getStringExtra("resultval").toString()

XML 部分如下所示:


              <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"/>

现在,我想将文本“PR Number”更改为“PR7438927438927”之类的内容。我该怎么做呢?使用这个:

findViewById<Text>(R.id.prNumberId).replaceWholeText(txt)

或使用:

findViewById<Text>(R.id.prNumberId).textContent = txt

向我抛出一个错误:类型参数不在其范围内。

如何使用我拥有的新变量分配 prNumberId 的值?

谢谢你。

我尝试通过 findByViewId 和 textContent 更改值,但它不起作用,因为它说有一个类型参数不在其范围内。它不接受 R.id.prNumberId 作为文本。

android kotlin
1个回答
0
投票

如果您尝试以错误的方式声明变量,就会发生这种情况。

这才是正确的做法

科特林:

val resultval : String = intent.getStringExtra("resultval").toString()
val prNumberTextView = findViewById<TextView>(R.id.prNumberId) 
prNumberTextView.text = resultval

XML:

<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"/>

但根据 Google 指南,Android 建议使用数据绑定

© www.soinside.com 2019 - 2024. All rights reserved.