[英]How do I set text of TextView to a string resource? (Java for android)
我想將TextView
組件的文本更改為我已經在strings.xml
創建的另一個文本。 當應用程序啟動時,顯示的文本存儲在strings.xml
,名稱為“help0”。 我想通過在名稱的 and 處放置另一個“0”,以編程方式將其設置為名稱為“help00”的字符串。 到目前為止,我已經編寫了這段代碼:
String help = "0";
help = help + "0";
final TextView help = (TextView) findViewById(R.id.help);
help.setText("@string/help" + help);
但是,當我運行應用程序時,文本更改為“@string/help00”,而不是我在strings.xml
help00 下存儲的文本。
我該如何解決這個問題?
因為您已經將 String 資源 id 與普通 String help
所以它作為String
。 您必須從 android 資源中獲取第一個資源字符串,然后需要使用本地 String 變量進行連接,例如,
help.setText(getResources().getString(R.string.help)+help);
正如我懷疑的那樣,如果您正在尋找動態字符串 id,您想要字符串資源 id 已經存在的 id 和 '0' 附加到它然后使用 ..
int resourceId = this.getResources().getIdentifier("@string/help" + help, "string", this.getPackageName());
接着
help.setText(resourceId);
試試這個
String help = "0";
final TextView tvHelp = (TextView) findViewById(R.id.help);
String yourString = getResources().getString(R.string.help);
tvHelp.setText(yourString +help)
我相信在運行時無法編輯 strings.xml 資源文件內容。 現在我假設你的 strings.xml 文件中有以下內容
<resources>
<string name="app_name">Application Name</string>
<string name="help0">Text1</string>
<string name="hellp00">Text2</string>
</resources>
如果您想將 TextView (id=@+id/textview) 上的文本從存儲為“help0”的值更改為存儲在“help00”中的值,請使用以下代碼:
String text= getString(R.string.help00);
TextView myTextView = findViewById(R.id.textview);
myTextView.setText(text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.