我正在使用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;
}
}
答案 0 :(得分: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();
}
});
}
答案 1 :(得分: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);
}
}