簡體   English   中英

如何從 Java 設置 Android TextView 的文本?

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

我目前正在開發一個 Android 應用程序,在我的應用程序運行時,我正在從 MainActivity 類中更改 TextView 對象中的文本。 為此,我使用了setText(CharSequence text)方法。 Android Studio 網站上此方法的文檔明確指出該方法的目的是“設置 TextView 的字符串值”。 但是,每當我嘗試將 Strings.xml 文件中的引用字符串作為此方法的參數傳遞時,我都會收到一個 NullPointerException,其中包含消息“Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on空對象引用。” 有人可以指導我為什么會發生此錯誤以及如何使用setText(CharSequence text)方法和引用的字符串作為參數嗎? 非常感謝!

確保初始化textview

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

還要確保在您的 setContentView xml 中,tv_name 在布局中被聲明為 TextView。

另一種方法來做到這一點

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