安卓在Java中用数组中的项填充ListView
我在listview的自定义行布局上有4个字段。我的数组中有4个字段要映射到listview上的这4个字段:
- cat_ID_PK
- 猫的名字
- 类别金额
- 你经常来吗
我不知道如何正确地做到这一点。以下是我目前掌握的情况:
private void loadListView(Expenses[] mExpenseArray) {
//This code will write the "name" variable correctly to the logcat, so I know I'm
getting the right values in my array.
String name = mExpenseArray[0].getCatName();
Log.v("log_tag", name);
ArrayAdapter<Expenses> adapter = new ArrayAdapter<Expenses>(getApplicationContext(), R.layout.list_row, R.id.catName, mExpenseArray);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
这段代码只填充R.id.catName
,但是当它填充它时,它看起来是这样的:mypackage@8ed455
(或者类似的东西)。其他字段都没有填充,我猜这与ArrayAdapter中的第三个参数R.id.catName
有关。但是,如果我去掉此参数,则会出现以下错误:
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
以下是我的自定义行布局的代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:layout_width="fill_parent"
安卓:layout_height="wrap_content"
安卓:background="@drawable/list_selector"
安卓:orientation="horizontal"
安卓:padding="5dip" >
<TextView
安卓:id="@+id/catName"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_marginLeft="15dip"
安卓:layout_centerVertical="true"
安卓:paddingBottom ="10dip"
安卓:text="@string/catName"
安卓:textColor="#040404"
安卓:textSize="25dip"
安卓:textStyle="bold"
安卓:typeface="sans" />
<TextView
安卓:id="@+id/catAmount"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_marginRight="27dip"
安卓:layout_centerVertical="true"
安卓:layout_alignParentRight="true"
安卓:paddingBottom ="10dip"
安卓:text="$45.00"
安卓:textColor="#040404"
安卓:textSize="25dip"
安卓:textStyle="bold"
安卓:typeface="sans" />
<TextView
安卓:id="@+id/catType"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_below="@+id/catName"
安卓:layout_alignLeft="@+id/catName"
安卓:paddingTop="5dip"
安卓:layout_centerHorizontal="true"
安卓:text="@string/catType"
安卓:textColor="#343434"
安卓:textSize="15dip" />
<TextView
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text="catID"
安卓:id="@+id/catID"
安卓:layout_alignBottom="@+id/catType"
安卓:layout_toRightOf="@+id/catType"
安卓:layout_toEndOf="@+id/catType"
安卓:layout_marginLeft="27dp"
安卓:visibility="invisible" />
</RelativeLayout>
如何将4个数组字段正确映射到ListView
# 1 楼答案
制作一个这样的自定义适配器,然后将值分配给文本视图
将这样的数组传递给适配器
然后在适配器中执行此操作
希望这有助于
# 2 楼答案
创建数组适配器的字符串类型并使用-
通过使用任何循环