mat*_*w3r 22 string variables android
我有一个xml文件,其中有字符串和字符串数组.我有一个班级,我点击一个listitem,而在另一个班级我列出其他项目.在xml中有一些字符串,其名称是被点击的项目修改名称,值是字符串数组名称.我找到了一个解决方案,如何将一个变量添加到getResources(9.getStringArray()但它不起作用.程序启动,但当我点击任何listitem时,我的活动就停止工作.我的类文件:
String artistpicked = extras.getString("artist");
String[] firstW = artistpicked.split(" ");
firstW[0] = firstW[0].trim();
String albumSearch = firstW[0] + "_code";
int getRes = getResources().getIdentifier(albumSearch, "string", getPackageName());
String setRes = String.valueOf(getRes);
int getRes2 = getResources().getIdentifier(setRes, "array", getPackageName());
String[] albums = getResources().getStringArray(getRes2);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, albums));
TextView t = (TextView) findViewById(R.id.albumName);
t.setText(setRes);
Run Code Online (Sandbox Code Playgroud)
TextView用于检查变量.albumSearch给出了"modifiedartistpicked_code",这很好.getRes给出了xml("something_array")的值,setRes给出了它的实际id号(getStringArray要求的值).getRes2与getRes相同,只是在那里检查它是否正常工作.当我注释掉接下来的两行,String albums []和setListAdapter时,程序可以正常工作,但它不会列出项目.
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="artists_array">
<item>code1 example</item>
<item>code2 example</item>
</string-array>
<string-array name="code1_array">
<item>item1</item>
<item>item2</item>
<item>item3</item>
</string-array>
<string-array name="code2_array">
<item>item1</item>
<item>item2</item>
<item>item3</item>
</string-array>
<string name="code1_code">code1_array</string>
<string name="code2_code">code2_array</string>
</resources>
Run Code Online (Sandbox Code Playgroud)
我希望我能写出我想做的事,问题是什么:)
更新:
@Marc Bernstein:因为我不知道它是code1_array.首先,我做了很多,如果选择的项目是x,那么我读了R.array.x_array等...
但是我遇到了问题,在xml中有字符串名称的大写字母.这就是为什么我讨厌xml,问题总是在那里:)这个xml只是一个例子,原来是更大的,这就是没有人能够提供帮助的原因.下次我会更加谨慎.
而且我现在更简单,因为你有权利它太复杂了.
Mar*_*ein 45
罪魁祸首是最有可能的
String[] albums = getResources().getStringArray(getRes2);
Run Code Online (Sandbox Code Playgroud)
而不是做
int getRes2 = getResources().getIdentifier(setRes, "array", getPackageName());
String[] albums = getResources().getStringArray(getRes2);
Run Code Online (Sandbox Code Playgroud)
为什么不用
String[] albums = getResources().getStringArray(R.array.code1_array);
Run Code Online (Sandbox Code Playgroud)
?
无论如何,根据你发布的内容,我认为你的strings.xml文件中实际上并不存在"数组"标识符.我看到了code1_array和code2_array.
小智 6
这是因为它试图动态确定它想要使用的数组。id from给出,比方说,在用户输入时,一些微调器/编辑文本框。这不是使用数据库,而是使用 xml 文件中的一些字符串。String[] albums = getResources().getStringArray(R.array.code1_array);