Android 如何使用CursorAdapter从ListView中删除选定项

Android 如何使用CursorAdapter从ListView中删除选定项,android,onclicklistener,android-cursoradapter,Android,Onclicklistener,Android Cursoradapter,我正在使用CursorAdapter,下面是我的适配器类。我的列表由两个文本视图和每行一个按钮组成。现在,单击按钮,我想从列表和数据库中删除所选项目。如何从数据库中获取所选项目的id,以便删除它,然后通知适配器(刷新列表) 我假设这个ID在游标中。然后,只需创建自己的类DeleteEntryOnClicklistener,该类实现OnClickListener,并让它在其构造函数中获取ID,并在单击时删除条目 如果我误解了你的问题,或者我不清楚,请发表评论,干杯:) 编辑: 在bindView(

我正在使用
CursorAdapter
,下面是我的适配器类。我的列表由两个文本视图和每行一个按钮组成。现在,单击按钮,我想从列表和数据库中删除所选项目。如何从数据库中获取所选项目的id,以便删除它,然后通知适配器(刷新列表)


我假设这个ID在游标中。然后,只需创建自己的类DeleteEntryOnClicklistener,该类实现OnClickListener,并让它在其构造函数中获取ID,并在单击时删除条目

如果我误解了你的问题,或者我不清楚,请发表评论,干杯:)

编辑:

bindView()
中,将OnClicklistener更改为如下内容:

long id = cursor.getLong(cursor.getColumnIndex(Helper.tbl_col_id));
button.setOnClicklistener(new DeleteEntryOnClicklistener(id));
public class DeleteEntryOnClicklistener implements View.OnClickListener {

    long id;

    public DeleteEntryOnClicklistener(long id) {
        this.id = id;
    }

    @Override
    public void onClick(View v) {
        database.deleteEntry(id);
    }

}
deletentryonclicklistener
应该如下所示:

long id = cursor.getLong(cursor.getColumnIndex(Helper.tbl_col_id));
button.setOnClicklistener(new DeleteEntryOnClicklistener(id));
public class DeleteEntryOnClicklistener implements View.OnClickListener {

    long id;

    public DeleteEntryOnClicklistener(long id) {
        this.id = id;
    }

    @Override
    public void onClick(View v) {
        database.deleteEntry(id);
    }

}

试试这样的东西:

@Override
public void bindView(View view, Context context, final Cursor cursor) {

    TextView txtName = (TextView) view.findViewById(R.id.txt_name);
    txtName.setText(cursor.getString(cursor.getColumnIndex(Helper
                                                           .tbl_col_username)));
    TextView txtPassword = (TextView) view.findViewById(R.id.txt_password);
    txtPassword.setText(cursor.getString(cursor.getColumnIndex(Helper
                                                           .tbl_col_password)));

    final String itemId = cursor.getString(cursor.getColumnIndex("id"));

    Button button = (Button) view.findViewById(R.id.btn_delete);
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            Log.d(TAG, "Button Click ");
            deleteRecordWithId(itemId);
            cursor.requery();
            notifyDataSetChanged();
        }
    });
}

是的,你是对的,我的id在光标中,我想从选中的项目中获取id,因此如何操作。我编辑了我的答案,也许现在我对代码的想象更清楚了。嗯,看起来不错,重新填充列表或刷新列表如何?可能是几年后我才出现,但上述解决方案的问题是,一旦从listview中删除一行,它的位置就会改变。但是它在数据库中的列id不是这样的,因为它是根据listview与游标绑定而自动递增的,如果您正在使用activity管理游标,那么onListItemClick会提供您想要的_id,但是在这里,您试图在bindView中单击按钮时获取_id,那么您必须在按钮单击之前使用_ID列名称并将其传递给按钮的单击,然后使用它…-)
cursor.requery()
现在不推荐使用