android - 仅使用 Kotlin 更改 textview 的值而不影响默认大小
问题描述
我正在以编程方式更改 textview 的值。
XML:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:text="test"
android:textSize="45px"/>
科特林:
name.text = "John Doe"
但是,当我使用上面的 Kotlin 代码时, textSize 也会更改为默认值。
我该如何保留textSize="45px"
?
解决方案
有 2 个选项。
第一个选项是,您替换px
为dp
. 然后你TextView
看起来像这样:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:text="test"
android:textSize="45dp"/>
在第二个选项中,您只需添加name.textSize= 45f
到您的代码中。然后你的 MainActivity 看起来像这样:
name.text = "John Doe"
name.textSize= 45f