为我的Android应用程序准备字符串资源时,我遇到了这样的问题。我需要两个包含12和13个项目的字符串数组,并且前11个项目对于这两个数组都是通用的。创建一个包含11个公共项的数组是一个好主意,然后创建两个需要的数组,其中包含来自“公共”数组的11个项以及1和2个其他项。但是,我找不到解决方法。可以引用一些xml资源,但是在我的情况下,有必要分别包含每个11个公共项。
预先感谢您的任何想法
在XML中,您可以将通用数组作为项目引用:
<resources>
<string-array name="common_array">
<item>name 1</item>
<item>name 2</item>
<item>name 3</item>
</string-array>
<string-array name="new_array">
<item>@array/common_array</item>
<item>name 4</item>
</string-array>
</resources>
然后在您的Java代码中,添加以下函数,该函数会将资源项转换为字符串列表:
List<String> getArrayItems(int resourceId, Resources resources) {
ArrayList<String> itemList = new ArrayList<>();
TypedArray typedArray = resources.obtainTypedArray(resourceId);
for (int i = 0; i < typedArray.length(); i++) {
int type = typedArray.getType(i);
if (type == TypedValue.TYPE_STRING) {
itemList.add(typedArray.getString(i));
} else if (type == TypedValue.TYPE_REFERENCE) {
int resIdOfArray = typedArray.getResourceId(i, 0);
List<String> itemsForGivenRes = Arrays.asList(resources.getStringArray(resIdOfArray));
itemList.addAll(itemsForGivenRes);
}
}
typedArray.recycle();
return itemList;
}
最后,您可以使用该功能获取以下项目的列表new_array
:
List<String> arrayItems = getArrayItems(R.array.new_array, getApplicationContext().getResources());
Log.d("MyAdapter", "onCreate: " + arrayItems.toString()); // should print MyAct: onCreate: [name 1, name 2, name 3, name 4]
请注意,在我的示例中,我仅考虑了字符串数组。只需少量更改,您就可以使函数适应不同的数组。
希望我的回答对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句