[英]Refresh list view when button delete is clicked inside custom adapter
我已经在此网络中搜索了此问题,但没有任何帮助。 许多人问同样的事情,但没有一个回答我的问题。 我有一个listView,其中的每一行都有一个按钮删除。 除了更新列表视图之外,我已完成所有工作。 此列表视图填充有存储在数据库中的信息。 对于每一行,我都有一个自定义的ListAdapter,并且处理此类内的Delete Button的onClick事件。
所以这是我设置自定义适配器的主要活动:
public class ClientsActivity extends ListFragment {
private Cursor mCursor;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_clients, container, false);
listEmployees(view);
...
}
private void listEmployees(View view){
//Get the list from DB and set other variables..
...
ListView lvEmployees = (ListView) view.findViewById (android.R.id.list);
ListClientCursorAdapter notes = new ListClientCursorAdapter(context, R.layout.activity_row_client, mCursor, from, to, 0);
lvEmployees.setAdapter(notes);
}
}
这是我的自定义适配器类:
public class ListClientsCursorAdapter extends SimpleCursorAdapter{
//Set the constructor and stuff
...
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
//Things that populate my rows
...
ImageButton buttonDelete = (ImageButton) v.findViewById(R.id.imageButtonDelete);
//I set in a bundle, the id of the employee that I want to delete.
final Bundle mArguments = new Bundle();
mArguments.putString("id", id);
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
alert.setMessage("are you sure?");
alert.setTitle("Deleting..");
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//I get from the bundle the Id of my employee
String id = mArguments.getString("id");
deleteEmployee(id);
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}});
return v;
}
private void deleteEmployee(String id) {
//Here I delete the item in the DB
//and everything works fine ..
...
//SOLUTION:
//HERE I HAVE TO REFRESH THE LIST. THIS IS HOW
this.changeCursor(DB.listCompanies(context));
this.notifyDataSetChanged();
}
}
据我所知,如果我从数组中获取列表的数据,则notifyDataSetChanged()会起作用。 但这不是我的情况。
任何帮助将不胜感激!
解决方案:在deleteEmployee方法中,我放入了以下代码(如您在上面的代码中看到的那样):
this.changeCursor(DB.listEmployees(context));
this.notifyDataSetChanged();
哪里
DB.listEmployees(context)
是用于从DB检索值以填充listView的方法。
因此,如您所见,我需要将旧游标更改为具有更新数据的新游标。
您重新查询mCursor,然后调用notifyDataSetChanged()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.