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

时间:2017-02-02 05:11:32

标签: java android textview charsequence

我目前正在开发一个Android应用程序,我在应用程序运行时从MainActivity类中更改TextView对象中的文本。为此,我使用setText(CharSequence text)方法。 Android Studio网站上的此方法文档明确指出方法的目的"设置TextView的字符串值。"但是,每当我尝试从我的Strings.xml文件中传递一个引用的字符串作为此方法的参数时,我会得到一个NullPointerException,其中包含消息"尝试调用虚方法' void android.widget.TextView。的setText(INT)'在null对象引用上。"有人可以指导我为什么会出现这个错误以及如何使用setText(CharSequence text)方法将引用的String作为参数?非常感谢你!

2 个答案:

答案 0 :(得分:1)

确保初始化textview

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

还要确保在setContentView xml中将tv_name声明为布局中的TextView。

答案 1 :(得分:-1)

另一种方法

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

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