8

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

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;
    }
}
4

2 回答 2

12

尝试这样的事情:

@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();
        }
    });
}
于 2011-12-08T11:15:21.890 回答
2

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

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

编辑:

在您的bindView()中,将 OnClicklistener 更改为以下内容:

long id = cursor.getLong(cursor.getColumnIndex(Helper.tbl_col_id));
button.setOnClicklistener(new DeleteEntryOnClicklistener(id));

DeleteEntryOnClicklistener应该看起来像这样:

public class DeleteEntryOnClicklistener implements View.OnClickListener {

    long id;

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

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

}
于 2011-12-07T14:01:10.797 回答