3

所以我有一个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)。

4

2 回答 2

2

这取决于您对R.layout.favorite. 如果您有此布局包含一个带有子 TextViews 的父视图,例如,您设置的标签用于 TextViews,而从 接收的 View vonListItemClick()是父 View。您需要确保收到与您设置的相同视图的标签:

    @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();      
    }    
于 2011-12-05T11:09:41.347 回答
0

您可能应该从适配器获取光标。这样,如果您的光标被替换,您仍然可以获得有效的光标。

@Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
       Cursor cursor =  adapter.getCursor();
       cursor.moveToPosition(position);
       String id = cursor.getString(cursor.getColumnIndex("primary key field name in database");
       Toast.makeText(getBaseContext(), "ID=" + id, 1).show();
    } 

注意: 您的适配器必须声明为SimpleCursorAdapter其他方式,否则您应该向下转换它。

于 2011-12-05T11:04:55.390 回答