android - 从与 SimpleCursorAdapter 绑定(bind)的 ListView 中获取所选项目

标签 android listview simplecursoradapter

我是 Android 开发的新手...来自 iPhone 和 .Net 背景。我见过与这个问题非常相似的问题,但没有一个涉及 SimpleCursorAdapter。

我有一个基本的 ListActivity,它使用 Cursor 将 SQLite 查询中的数据绑定(bind)到我的 ListView:

ListAdapter adapter = new SimpleCursorAdapter(
        this, 
        android.R.layout.simple_list_item_1,  
        c,        
        new String[] {"name"},   
        new int[] {android.R.id.text1}); 

setListAdapter(adapter);

然后当一个项目被点击时:

public void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position,  id);

    //Difference between this:
    Cursor c = (cursor)l.getItemAtPosition(position);
    //and this??
    Cursor c = (Cursor)l.getAdapter().getItem(position);

    int categoryId = c.getInt(0);
}

这是获取所选元素 id 的正确方法吗?这似乎很奇怪,因为我认为在数据库关闭后(即在我绑定(bind)之后)我不能使用我的光标。当我似乎无法找到从该 id 获取实际项目的方法时,传入的 id 有什么意义?另外,我不明白为什么 getItemAtPosition() 会返回一个游标......游标绑定(bind)到整个列表;不只是一排。最后,如果这是正确的,那么显示的两种获取光标的方式有区别吗?谢谢。

最佳答案

所以有几点:在获取光标后,您要调用 startManagingCursor。这将游标的生命周期与 Activity 的生命周期联系起来(因此当 Activity 被销毁时,游标会被关闭/清理)。

startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(
        this, 
        android.R.layout.simple_list_item_1,  
        c,        
        new String[] {"name"},   
        new int[] {android.R.id.text1}); 
setListAdapter(adapter);

此外,数据库没有关闭,游标通常与数据库保持实时连接(因此 ListView 可以滚动并执行可能需要将来访问游标内容的那种性质的事情.

对于您的核心问题,在 onListItemClick 中执行此操作的最简单方法是:

Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);

然后您可以使用 c.getLong(0) 来获取 id(假设您将 id 列作为第一列获取,这通常是这种情况)。但是,请注意 id 是作为签名的一部分传入的(请参阅 public void onListItemClick(ListView l, View v, int position, long id) 中的最后一个参数)所以你真的不需要再次获取它(但如果你想烧掉循环,你当然可以)。要访问其他列,您可以执行相同的操作,只需更改列索引即可。

希望对您有所帮助。

关于android - 从与 SimpleCursorAdapter 绑定(bind)的 ListView 中获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6156836/

相关文章:

android - 如何解决此错误:无法解决:com.android.support:appcompat-v7:26.1.0

android - 在 Android 中为 SimpleCursorAdapter 添加日期分隔符

android - Simplecursoradaptor 中的自定义文本字体

android - 无法使 AlphabetIndexer 工作

android - fragment 自定义动画

android - 无法点击 robotium 上的操作栏

java - 如何从另一个类更改 imageview 源?

android - 如何配置ListView自动改变高度?

android - 如何更改Gridview中不同行的列数

c++ - ListView 的 ImageList 的大小应该是多少?