我正在开发一个java Android应用程序,我有一个XML资源,它看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- first pattern -->
<integer-array name="pattern_a">
<item>1</item>
<item>0</item>
<item>1</item>
</integer-array>
<!-- second pattern -->
<integer-array name="pattern_b">
<item>1</item>
<item>1</item>
<item>0</item>
</integer-array>
<!-- broad configuration -->
<string name="config_broad_name">broad</string>
<integer-array name="config_broad_pattern">@array/pattern_a</integer-array>
<!-- small configuration -->
<string name="config_small_name">small </string>
<integer-array name="config_small_pattern">@array/pattern_b</integer-array>
</resources>
我正在创建一个配置并从我的资源文件中设置一些值,这似乎很容易直接...
public Configuration createConfiguration(){
Configuration configBroad = new Configuration();
String configName = getResources().getString(R.string.config_broad_name);
int[] pattern = getResources().getIntArray(R.array.config_broad_pattern);
configBroad.setName(configName);
configBroad.setPattern(pattern);
return configBroad;
}
问题:int [] pattern是一个空int [](如int [] {})
真正有用的东西,如下:
int patternId = getArrayId(getResource(), R.string.config_broad_pattern);
configBroad.setPatternId(patternId); //setting just the id, not the whole pattern
然后我可以检索值本身,甚至更好 - 在我的配置而不是数组上设置id。
我知道,有关如何使用string [](如array_of_array)和@image /...-数组处理此问题的大量解释但我找不到任何一个整数数组(特别是在寻找Typed-Array时,我找不到帮助)
答案 0 :(得分:0)
好的,我花了很多时间来解决这个问题......
当你想从XML引用另一个定义的值时,你必须将该值称为STRING,至少如果你遵循我的解决方案......
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- first pattern -->
<integer-array name="pattern_a">
<item>1</item>
<item>0</item>
<item>1</item>
</integer-array>
<!-- second pattern -->
<integer-array name="pattern_b">
<item>1</item>
<item>1</item>
<item>0</item>
</integer-array>
<!-- broad configuration - notice difference on reference -->
<string name="config_broad_name">broad</string>
<string name="config_broad_pattern">@array/pattern_a</string>
<!-- small configuration -->
<string name="config_small_name">small </string>
<string name="config_small_pattern">@array/pattern_b</string><!-- same here -->
</resources>
当然我们使用与上面相同的代码,但我们必须稍微调整一些地方:
public Configuration createConfiguration(){
Configuration configBroad = new Configuration();
String configName = getResources().getString(R.string.config_broad_name);
String refPatternName = getResources().getString(R.string.config_broad_pattern);
refPatternName = refPatternName.replace("@",""); //removing @-prefix
int refPatternId = Integer.parseInt(str); //this value now is the same as R.array.pattern_a
configBroad.setName(configName);
configBroad.setPatternId(refPatternId);
return configBroad;
}
答案 1 :(得分:-2)
对我来说,这是一个简单的问题。在XML中只使用字符串数组,然后在java代码中将其转换为全部的整数。