SimpleCursorAdapter和ViewBinder - 将数据绑定到ListView的项目上点击检索 [英] SimpleCursorAdapter and ViewBinder - Binding data to ListView items to be retrieved on click
问题描述
所以我有一个的ListView
(使用 ListActivity
)我是从一个填充 SQLiteDatabase
。我试图给该行的ID(PK)连接到视图,使 onListItemClick
各列表项的,我可以使用该ID做的东西。
So I've got a ListView
(using a ListActivity
) that I'm populating from a SQLiteDatabase
. I'm trying to attach the ID (PK) of the row to the view, so that onListItemClick
of each list item, I can do stuff with that ID.
我读过的任意数据可以被设置为查看
使用 setTag
和<$ C检索$ C> getTag (我没有实际上有这项工作还没有成功,所以这可能是问题)。下面是我使用的是什么(为了简化/简洁)的缩减版本下来:
I've read that arbitrary data can be set to a View
using setTag
and retrieved with getTag
(I haven't actually had this work successfully yet, so this may be the problem). Here's a pared down version of what I'm using (for simplicity/brevity):
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被填充
和吐司
没有显示出来,但它总是ID = NULL
,所以显然ID没有被中设置的 ViewBinder
来电 setTag
(或不被检索财产 getTag
)。
The ListView
is being populated, and the Toast
does show up, but it's always "ID=null"
, so apparently the ID isn't being set in the ViewBinder
call to setTag
(or isn't being retrieved property with getTag
).
推荐答案
这取决于具体的实现 R.layout.favorite
的。如果您有这方面的布局包含子TextViews用于例如父视图您设置的标签为TextViews同时从 onListItemClick()
是父查看收到的视图V。你需要确保你收到标签为你使用设置了同样的观点:
This depends on your implementation of R.layout.favorite
. If you have this layout contains a parent view with child TextViews for e.g. the tag you set is for the TextViews while the View v received from the onListItemClick()
is the parent View. You need to make sure that you receive the tag for the same view you set by using:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getChild(0).getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
这篇关于SimpleCursorAdapter和ViewBinder - 将数据绑定到ListView的项目上点击检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!