我想custom adapter为我的列表视图创建一个。有没有任何文章可以指导我如何创建一个并解释它是如何工作的?
custom adapter
public class ListAdapter extends ArrayAdapter<Item> { private int resourceLayout; private Context mContext; public ListAdapter(Context context, int resource, List<Item> items) { super(context, resource, items); this.resourceLayout = resource; this.mContext = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(mContext); v = vi.inflate(resourceLayout, null); } Item p = getItem(position); if (p != null) { TextView tt1 = (TextView) v.findViewById(R.id.id); TextView tt2 = (TextView) v.findViewById(R.id.categoryId); TextView tt3 = (TextView) v.findViewById(R.id.description); if (tt1 != null) { tt1.setText(p.getId()); } if (tt2 != null) { tt2.setText(p.getCategory().getId()); } if (tt3 != null) { tt3.setText(p.getDescription()); } } return v; } }
这是我用于我的项目的一个类。您需要收集要显示的项目,在我的情况下是<Item>. 您需要覆盖View getView(int position, View convertView, ViewGroup parent)方法。
<Item>
View getView(int position, View convertView, ViewGroup parent)
R.layout.itemlistrow定义ListView.
R.layout.itemlistrow
ListView
<?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="fill_parent"> <TableRow android:layout_width="fill_parent" android:id="@+id/TableRow01" android:layout_height="wrap_content"> <TextView android:textColor="#FFFFFF" android:id="@+id/id" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="id" android:textStyle="bold" android:gravity="left" android:layout_weight="1" android:typeface="monospace" android:height="40sp" /> </TableRow> <TableRow android:layout_height="wrap_content" android:layout_width="fill_parent"> <TextView android:textColor="#FFFFFF" android:id="@+id/categoryId" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="categoryId" android:layout_weight="1" android:height="20sp" /> <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1" android:textColor="#FFFFFF" android:gravity="right" android:id="@+id/description" android:text="description" android:height="20sp" /> </TableRow> </TableLayout>
在这样的MainActivity定义ListView中,
MainActivity
ListView yourListView = (ListView) findViewById(R.id.itemListView); // get data from the table by the ListAdapter ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, List<yourItem>); yourListView .setAdapter(customAdapter);