我目前面临一个愚蠢的问题。我有一个带有自定义适配器(扩展 CursorAdapter)的 ListView 。
它显示带有不同按钮(分享、点赞、删除)的自定义 View 。对于删除按钮,它有一个警告对话框来确认删除项目。当用户确认时,该项目将从数据库中删除。一切正常,直到这里。
我的问题是,如何使用我的新数据集有效地更新我的 ListView ?
非常感谢您的帮助。
代码:
public class CommentCursorAdapter extends CursorAdapter{
(...)
@Override
public void bindView(View view, Context arg1, Cursor cursor) {
(...)
holder.list_item_comment_discard_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String _id = v.getTag().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle("Delete");
builder.setMessage("Do you want to delete "+_id);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
DBAdapter dba = new DBAdapter(mActivity);
dba.open();
dba.remove(_id);
Log.i("TAAG", "removed: "+_id);
dba.close();
// How to update the listview ??
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.show();
}
});
holder.list_item_comment_discard_btn.setTag(_id);
(...)
}
(...)
}
最佳答案
如果您使用 LoaderManager 来管理游标的生命周期(这是执行此操作的正确方法),您只需调用 restartLoader,然后在 onLoadFinished 中(重新)设置适配器的游标。您的 ListView 将重新加载更新的数据。
您的 Activity 或 fragment 中的游标管理应该以非常简单直接的方式完成:
为了初始化你的游标:
public void onCreate(Bundle savedInstanceState) { // or onStart // ... this.getLoaderManager().initLoader(MY_CURSOR_ID, null, this); // ... } public Loader<Cursor> onCreateLoader(int id, Bundle args) { // TODO: create a cursor loader that will load your cursor here } public void onLoadFinished(Loader<Cursor> arg0, final Cursor arg1) { // TODO: set your cursor as the cursor of your adapter here; } public void onLoaderReset(Loader<Cursor> arg0) { // TODO: set null as the cursor of your adapter and 'free' all cursor // references; }
然后,当您需要重新加载数据时:
this.getLoaderManager().restartLoader(MY_CURSOR_ID, null, this);
关于android - 如何管理删除 CursorAdapter 上的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227225/