如何在Android中使用XML使用资源数组?

问题描述:

我是Android开发的新手,并且在管理Android资源方面遇到问题.我想用ImageView和TextView创建一个listView.

I am new in Android development and facing a problem with managing Android resources. I want to create a listView with an ImageView and a TextView.

以下是我的实现效果很好的实现,但实际上我想使用之前创建的数组,如下所示:

Following is my implementation which works fine, but actually I wanted to use arrays which I created before like this:

int[] img = getResources().getIntArray(R.Array.img);

package com.simplelistviewwithlistactivity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;

public class ListActivityS extends ListActivity {
    int[] img = { R.drawable.r1, R.drawable.r2, R.drawable.skycubemap1,
            R.drawable.skycubemap1, R.drawable.skycubemap2,
            R.drawable.skycubemap3, R.drawable.skycubemap4,
            R.drawable.skycubemap5 };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getListView().setDividerHeight(2);
        getListView().setAdapter(new BindDataAdapter(this, img, item));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(item[position] + " is clicked.");
        builder.setPositiveButton("OK", null);
        builder.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_list, menu);
        return true;
    }

    private String item[] = { "This is list Item1", "This is list Item2",
            "This is list Item3", "This is list Item4", "This is list Item5",
            "This is list Item6", "This is list Item8", "This is list Item8"

创建如下所示的XML,并将其放入res/values/arrays.xml

Create an XML like below and put it in res/values/arrays.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="icons">
        <item>@drawable/home</item>
        <item>@drawable/settings</item>
        <item>@drawable/logout</item>
    </array>
    <array name="colors">
        <item>#FFFF0000</item>
        <item>#FF00FF00</item>
        <item>#FF0000FF</item>
    </array>
</resources>

然后使用如下代码:

Resources res = getResources();
TypedArray icons = res.obtainTypedArray(R.array.icons);
Drawable drawable = icons.getDrawable(0);

TypedArray colors = res.obtainTypedArray(R.array.colors);
int color = colors.getColor(0,0);

来源: http://developer.android.com/guide/topic/resources/more-resources.html