我設置了下面的 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();
}
});
}