所以我有一个ListView(使用 a ListActivity)我从 a 填充SQLiteDatabase。我正在尝试将行的 ID (PK) 附加到视图,以便对于onListItemClick每个列表项,我可以使用该 ID 执行操作。
我读过可以将任意数据设置为ViewusingsetTag和检索 with getTag(我实际上还没有成功完成这项工作,所以这可能是问题所在)。这是我正在使用的精简版本(为了简单/简洁):
public class Favorites extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FavoritesDB db = FavoritesDB.getInstance(this);
Cursor c = db.fetchFavorites();
startManagingCursor(c);
String[] columns = new String[] { "_id" };
int[] to = new int[] { R.id.word };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.favorite, c, columns, to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
view.setTag(cursor.getInt(0));
return true;
}
});
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
}
ListView正在填充,并且确实出现Toast了,但它总是"ID=null",所以显然 ID 没有在ViewBinder调用中设置setTag(或者没有被检索属性getTag)。