我想知道是否有人可以进一步解释如何在从SQLite数据库填充的列表视图中实现删除按钮。我已经阅读了以下问题的回复,这些问题基本上也是我所要求的,但我不理解它:
How can I implement a delete button in a ListView and delete from database?
在我的自定义行.xml文件中,我包含了一个删除按钮,用于实现方法delete()onClick。顺便说一下,它还包括一个警报对话框。这是我到目前为止我的delete()方法的代码;每当我尝试使用它时,它永远不会获得正确的活动条目。
public void delete(View view){
final int position = listview.getPositionForView((View) view.getParent());
String id = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_ID));
AlertDialog.Builder myDialog = new AlertDialog.Builder(MainActivity.this);
myDialog.setTitle("Delete activity entry \"" + id + "\"?");
myDialog.setPositiveButton("DELETE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
mySQLiteAdapter.delete(position);
cursor.requery();
}
});
myDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialog.show();
}
答案 0 :(得分:0)
解决方案是实现自定义ArrayAdapter。
public class MyArrayAdapter extends ArrayAdapter<YourObject>
{
private ArrayList<YourObject> items;
public LiftArrayAdapter(Context context, int textViewResourceId, ArrayList<YourObject> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_view_xml, null);
}
final YourObject obj = items.get(position);
TextView lblLift = (TextView) v.findViewById(R.id.lbl_lift);
ImageButton btnDelete = (ImageButton) v.findViewById(R.id.btn_delete);
btnDelete .setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//TODO delete 'obj' from database
}
});
return v;
}
}
然后,将对象列表绑定到listview:
List<YourObject> list = ...
MyArrayAdapter myArrayAdapter = new MyArrayAdapter (.., .. , list);
listView.setAdapter(myArrayAdapter);