ListView
显示数据使用Adapter
(通常使用的实现之一BaseAdapter
,SimpleAdapter
或ArrayAdapter
使用)。
Adapter
类保存对要显示的项目的引用,并且还有一个特殊的方法getItemId(int position)
,它必须返回 ListView 中某个位置的项目的 ID。
所以,假设我们有一个 Item 类:
public class Property{
public final long id;
public final String name;
public final long price;
public Property(long id, String name, long price){
this.id = id;
this.name = name;
this.price = price;
}
}
映射到一些数据库记录:
| _id | name | price |
|-----|------|-------|
| 1 | abcd | 123 |
| 2 | efgh | 456 |
然后我们可以使用 anArrayAdpater
来显示 a 中的一组Property
项目ListView
:
public class PropertyAdapter extends ArrayAdapter<Property>{
public PropertyAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public long getItemId(int position) {
return getItem(position).id;
}
}
你可以得到项目的ID:
ListView listView = <some list view>;
PropertyAdapter propertyAdapter = < adapter for list view >;
listView.setAdapter(propertyAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int itemId = propertyAdapter.getItemId(i);
//-- this item Id is same as returned by getItemId(),
//-- which is id field of Property class
//-- which is id column in database
}
});