在 ListView 中使用 CursorAdapter 移除一个选择项目

我设置了下面的 adapter 类,包含 CursorAdapter 方法。在列表中包含两个文本视图,并在每行设置一个按钮。现在点击按钮时,我想从 list 中删除选择的项目,同时在数据库中也删除。
如何从数据库中获得选项的id,那样我就可以删除选项,然后告知adapter,刷新list。

public class MyAdapter extends CursorAdapter {

    Cursor c;
    LayoutInflater inflater;
    Context context;
    private String TAG = getClass().getSimpleName();

    public MyAdapter(Context context, Cursor c) {
        super(context, c);
        this.c = c;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    @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)));

        Button button = (Button) view.findViewById(R.id.btn_delete);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Log.d(TAG, "Button Click ");
            }
        });
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View v = inflater.inflate(R.layout.row, null); 
        return v;
    }
}

试一下:

@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"字段,类型用long比较好。

mSQLiteDatabase.delete(TABLE_NAME,"_id = " + getItemId(cursor.getPosition()), null);

既然是cursorAdapter,点击具体一行时可以调整cursor的位置再利用 cursor.getString或cursor.getInt这类方法来获取你需要的数据,cursor应该有你说得的id字段吧,没有就在查询的时候把id字段加上就行了。你的这个需求是不是应该先删除数据库的数据,只有数据删除成功了才删除list显示中条目,至于后面的更新界面,adapter里应该有个changeCursor方法可以达到你要的效果。