简体   繁体   English

如何从 Java 设置 Android TextView 的文本?

[英]How do I set the text of an Android TextView from Java?

I am currently working on an Android application where I am changing the text in a TextView object while my app is running, from within the MainActivity class.我目前正在开发一个 Android 应用程序,在我的应用程序运行时,我正在从 MainActivity 类中更改 TextView 对象中的文本。 To do this, I am using the setText(CharSequence text) method.为此,我使用了setText(CharSequence text)方法。 This method's documentation on the Android Studio website explicitly states that the purpose of the method "Sets the string value of the TextView." Android Studio 网站上此方法的文档明确指出该方法的目的是“设置 TextView 的字符串值”。 However, whenever I try to pass a referenced string from my Strings.xml file as a parameter for this method, I get a NullPointerException with the message "Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference."但是,每当我尝试将 Strings.xml 文件中的引用字符串作为此方法的参数传递时,我都会收到一个 NullPointerException,其中包含消息“Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on空对象引用。” Can somebody please guide me as to why this error is occurring and how use the setText(CharSequence text) method with a referenced String as a parameter?有人可以指导我为什么会发生此错误以及如何使用setText(CharSequence text)方法和引用的字符串作为参数吗? Thank you so much!非常感谢!

Make sure to initialize textview确保初始化textview

TextView tvName = (TextView) findViewById(R.id.tv_name);
tvName.setText(getResources().getString(R.string.name_xml));

Also make sure in your setContentView xml the tv_name is declared as TextView in the layout.还要确保在您的 setContentView xml 中,tv_name 在布局中被声明为 TextView。

another way to do this另一种方法来做到这一点

TextView textview  = (TextView)findViewById(R.id.text);//get the view of textview

//set the text for textview
textview.setText("text you want to set");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM