我有一个包含数据库数据的列表。 我想在每个列表项中都有一个按钮,onClick将从数据库中删除此项。 以下是我如何从数据库中获取数据并将其显示在列表中:
DB entry=new DB(this);
entry.open();
Cursor cursor = entry.getData();
startManagingCursor(cursor);
ListView list=(ListView)findViewById(R.id.list);
String[] columns = new String[] { DBHelper.NAME, DBHelper.SURNAME};
int[] to = new int[] { R.id.textView01,R.id.textView02};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, columns, to);
list.setAdapter(mAdapter);
entry.close();
所以,我的问题是:如何在每个列表项中创建一个可点击按钮
编辑: 这是我创建的适配器:
public class myAdapter extends BaseAdapter {
private Context mContext;
final Drawable delete_btn;
private ImageButton imageButton;
private LayoutInflater inflater;
private List<ITEMS> items = new ArrayList<ITEMS>();
public myAdapter(Context ctx) {
mContext = ctx;
inflater = LayoutInflater.from(mContext);
delete_btn = ctx.getResources()
.getDrawable(R.drawable.delete_btn);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View btv = null;
try {
btv = inflater.inflate(R.layout.row, null);
TextView name = (TextView) btv.findViewById(R.id.textView01);
name.setText(DBHelper.NAME);
TextView surname = (TextView) btv.findViewById(R.id.textView02);
surname.setText(DBHelper.SURNAME);
imageButton = (ImageButton) btv.findViewById(R.id.delete_btn);
imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
return btv;
}
public void addItem(ITEM it) {
items.add(it);
}
public void setListItems(List<ITEM> lit) {
items = lit;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int arg0) {
return items.get(arg0);
}
@Override
public long getItemId(int arg0) {
return arg0;
}
}