背景: 对于我的 Android 应用程序,我使用的是 ListView 和列表项触发声音,它们作为 .ogg 文件存储在/res/raw/目录中。我能够通过存储在 strings.xml 中的字符串数组自动设置 ListView 的文本标签和长度,现在我需要一个额外的 ResID 数组,我想将其存储在那里,以便将来方便扩展 ListView .
工作代码: 对于字符串数组,我使用以下代码: Java fragment :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
titles = getResources().getStringArray(R.array.listoftitles);
XML(字符串.xml):
<string-array name="listoftitles">
<item>Title1</item>
<item>Title2</item>
</string-array>
有问题的代码: Java fragment :
filenames = new int[]{R.raw.both1, R.raw.both2, R.raw.both3, R.raw.both4, R.raw.both5
, R.raw.both6, R.raw.both7, R.raw.both8, R.raw.both9, R.raw.both10, R.raw.both11
, R.raw.both12, R.raw.both13, R.raw.both14, R.raw.both15, R.raw.both16, R.raw.both17
, R.raw.both18, R.raw.both19};
目标:
private void populatemylist() {
for (int i = 0; i < titles.length; i++) {
itemsdb.add(new Item(titles[i], descriptions[i], filenames[i]));
}
}
方法 populatemylist() 的便利性至关重要,虽然可以很容易地从 xml 数组中获取 titles[] 和 descriptions[],但它不适用于文件名,我需要将其作为 ResID/int 值。我尝试使用一个整数数组,以及一个带有 TypedArray Java 后端的通用数组,但这似乎是针对可绘制对象的,我只是无法让它从/res/raw/文件夹中获取任何内容。我想要一个简单的数组解决方案,它以
的方式进入 strings.xml<item>R.raw.both1</item>
和一个简单的 java 后端,它为我提供了一个包含这些文件名的 int 数组。
最佳答案
您需要使用 TypedArray,如果您有任何问题请告诉我,否则祝您好运!
文件名.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="random_imgs">
<item>@raw/both1</item>
<item>@raw/both2</item>
<!-- ... -->
</string-array>
</resources>
private int getFileNameAtIndex(int index) {
TypedArray fileNames = getResources().obtainTypedArray(R.array.filenames);
// or set you ImageView's resource to the id
int id = fileNames.getResourceId(index, -1); //-1 is default if nothing is found (we don't care)
fileNames.recycle();
return id;
}
关于java - 如何将此 java 数组转换为 xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479268/