gpt4 book ai didi

android - 如何在Android中使用xml使用资源数组?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:50:11 24 4
gpt4 key购买 nike

我是 Android 开发的新手,面临管理 Android 资源的问题。我想创建一个带有 ImageView 和 TextView 的 listView。

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

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

<?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/topics/resources/more-resources.html

关于android - 如何在Android中使用xml使用资源数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16616458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com