改变TextView的文本

31

我正在尝试从代码中更改我的TextView文本。

这是我的xml的样子:

XML:
<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal" />

代码如下:

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
setContentView(tv1);

我的设备出现了错误,并且应用程序停止了。我尝试展示一个 TextView(未连接到 XML 的 TextView),它可以工作。


2
TextView不能被设置为您的父视图。您需要用LinearLayout将TextView包围起来。 - SamSPICA
展示一下你的onCreate方法,你的XML文件叫什么名字? - Hades
3个回答

75

你的方法是不正确的。我认为会出现空指针异常(下次请发布日志记录)

在查找视图之前,您需要首先指定正在使用的布局。

Java:

// Specify the layout you are using.
setContentView(R.layout.yourlayout);

// Load and use views afterwards
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");

Kotlin:

// Specify the layout you are using.
setContentView(R.layout.yourlayout)

// Load and use views afterwards
val tv1: TextView = findViewById(R.id.textView1)
tv1.text = "Hello"

点击这里学习您想了解的内容


谢谢大家的快速回答。Abhi感谢,现在它正常工作了。 - Imri Persiado
@ImriPersiado 然后你可以接受答案,只需在我的答案左侧打勾即可 :P - Abhi
@ChrisMcJava - Kotlin版本不应该使用synthetic吗? - charles-allen
1
@AjahnCharles:Kotlinx synthetic不再是推荐的标准实践:https://android-review.googlesource.com/c/platform/frameworks/support/+/882241来自Google Android的解释:https://www.reddit.com/r/androiddev/comments/ala9p2/why_kotlinx_synthetic_is_no_longer_a_recommended/efdvpkg/ - ChrisMcJava

5

remove this.. setContentView(tv1);


3

我遇到了同样的问题。我的应用也停止了。 实际上,我是在函数/方法外编写代码的。为了解决这个问题,需要在函数/方法内部添加以下代码:

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");

必须在函数/方法内部。 (可以是用户定义的) (我是 Android Studio 的新手,所以我不知道问题背后的原因,但我知道如何解决这个问题。也许这对于新手有所帮助,尽管这个问题已经有8年了。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接