我正在尝试从代码中更改我的 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
)并且它起作用了。
最佳答案
您的方法不正确。我认为这将是空指针异常(下次发布日志猫)
在查找 View 之前,您需要先指定要使用的布局。
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"
Click Here准确地学习你想知道的
关于android - 更改 TextView 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452991/