Android 更改文本查看文本

Android 更改文本查看文本,android,textview,Android,Textview,我正在尝试更改代码中的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
文本

这就是我的xml的样子:

XML:
<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal" />
我的设备出现错误,应用程序停止。
我试图显示
TextView
(未连接到XML
TextView
),但成功了。

删除此<代码>设置内容视图(tv1)

您的方法不正确。我认为这将是空指针异常(下次发布日志cat时)

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

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");
// 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"
Kotlin:

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

为了准确地学习你想知道的内容,我也遇到了同样的问题。我的应用程序也停止了。 实际上,我是在函数/方法之外编写代码的。为了解决这个问题,这些线

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
必须位于函数/方法内部。(可由用户定义)
(我是android studio的新手,所以我不知道问题背后的原因,但我只知道如何解决这个问题。尽管这个问题已经存在了8年,但这可能对新问题有所帮助。)

TextView不能设置为您的父视图。您必须在文本视图周围使用线性布局。^correct告诉我们您的oncreate方法,您的xml文件名是什么?谢谢大家这么快回答。Abhi谢谢,现在它开始工作了。@ImriPersiado然后你可以接受答案,只需在我答案的左侧打勾:P@ChrisMcJava-Kotlin版本不应该使用合成的吗?@AjahnCharles:Kotlinx synthetic不再是推荐的标准做法:谷歌Android的解释: