gpt4 book ai didi

java - 是否可以替换 R.string 末尾的名称。使用变量调用

转载 作者:行者123 更新时间:2023-12-02 04:23:29 26 4
gpt4 key购买 nike

嗨,抱歉,这里是菜鸟,所以不太了解术语。我想要做的是替换这样的命令的结尾

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

使用更动态的内容,用变量替换“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 拒绝,这给我显示了红线。

请帮忙,也请善意,因为我仍在学习如何编码,所以我不知道

最佳答案

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

通过这一行,您可以获得所需字符串资源的 id。然后你可以将它传递给你的TextView:

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

关于java - 是否可以替换 R.string 末尾的名称。使用变量调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32478977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com