Search code examples
androidandroid-listviewandroid-viewbinder

getTag() always null in onListItemClick


I have a ListView that I'm populating with a CursorAdapter like this:

SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() {
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        if(columnIndex == cursor.getColumnIndex(MyTableColumns._ID))
        {
            view.setTag(cursor.getInt(columnIndex));
        }
        // some other stuff
    }
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.my_item_renderer, cursor, from, to);
adapter.setViewBinder(viewBinder);

The aim is to get the ID from the list item clicked:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    Object obj = v.getTag();
    int myId = Integer.parseInt(obj.toString());
}

However this is always returning null. What am I overlooking? For now I'm just using a hidden text field but I'd like to know what I was doing wrong.


Solution

  • onListItemClick() provides you with a view that is the row in the list. ViewBinder binds values to the TextViews inside this row. Thus the view you call setTag() on is not the same as the view you call getTag() on.

    You can either extend SimpleCursorAdapter so you can call setTag() on the correct view, or you can get the first child view of v in onListItemClick() and get the tag of that.