繁体   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