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

相关文章:

android - 新的 Android Studio Activity 设计模式 content_main.xml

android - 发现多个文件的操作系统独立路径为 'lib/armeabi-v7a/libarcore_sdk_jni.so'

Android如何去掉椭圆末尾的问号

html - 从 XML 中的 html 格式的字符串资源设置 TextView 文本

android - 您必须为 TextView android 错误提供资源 ID

java - 扩展 NavigationDrawer Activity

Android View.OnKeyListener : click once, 执行两次

java - 从我的 Assets 中解析 JSON 数据

android - 用 TextViews 结束椭圆问题

android - 使用 android :singleLine and android:autoLink 时按钮文本不可见