如何将此java数组转换为xml?

时间:2013-07-04 23:34:19

标签: java android xml arrays

背景: 对于我的Android应用程序,我使用ListView和列表项触发声音,这些声音存储为/ res / raw /目录中的.ogg文件。我能够通过strings.xml中存储的字符串数组自动设置listview的文本标签和长度,现在我需要一个额外的ResID数组,我希望将其存储在那里,以便将来方便地扩展listview

工作代码: 对于字符串数组,我使用以下代码: Java Fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
...
titles = getResources().getStringArray(R.array.listoftitles);

XML(strings.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()的便利性是至关重要的,虽然titles []和description []很容易从xml数组中获取,但它不适用于文件名,我需要它作为ResID / int值。我尝试使用整数数组,以及带有TypedArray Java后端的通用数组,但这似乎是针对drawables而我无法从/ res / raw /文件夹中获取任何内容。我想有一个简单的数组解决方案,以

的方式在strings.xml中
<item>R.raw.both1</item>

和一个简单的java后端,它为我提供了这些文件名的int数组。

1 个答案:

答案 0 :(得分:1)

您需要使用TypedArray,如果您有任何其他问题,请告诉我们!

filenames.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;
    }