簡體   English   中英

是否可以在R.string的末尾替換名稱。 用變量調用

[英]Is it possible to replace the name at the end of the R.string. call with a variable

對不起,這里的菜鳥真不懂術語。 我想做的就是替換這樣的命令結尾

((TextView) findViewById(R.id.rr)).setText(R.string.Constitution);

替換為更具動態性的內容,用構成一詞代替“構成”一詞,該詞是對strings.xml資源中的字符串的引用。 我認為這是可行的方式,但確實如此

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    String textFromSpinner = spinner.getSelectedItem().toString();

    if (textFromSpinner.contains(" ")){
        textFromSpinner = textFromSpinner.replaceAll(" ", "_");
    }

    String valueToGet = "R.string" + textFromSpinner;

    ((TextView) findViewById(R.id.rr)).setText(valueToGet);

}

拒絕之后,我還嘗試了許多變體,但這些變體立即被Android Studio拒絕,但顯示出紅線。

請幫助,而且,請保持友善,因為我仍在學習如何編碼,所以我不知道legebale

您可以在運行時調用getResource().getIdentifier()方法以按資源名稱檢索資源。 檢查以下內容: http : //developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

int stringId = context.getResources().getIdentifier(textFromSpinner, "string", context.getPackageName());

通過此行,您可以獲取所需字符串資源的ID。 然后,您可以將其傳遞給TextView

((TextView) findViewById(R.id.rr)).setText(stringId);
<string name="hello_world">Hello %1$s</string>

替換@runtime

String str = "World";
str = String.format(getResources().getString(R.string.hello_world), str );
 int searchId = getResources().getIdentifier(textFromSpinner, "string", this.getPackageName());
    if (searchId != 0){
        ((TextView) findViewById(R.id.rr)).setText(searchId);
    } else {
        ((TextView) findViewById(R.id.rr)).setText(R.string.Please_Select_Option);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM