【问题标题】:How to refresh the ListView after change the data with the DialogFragment?使用 DialogFragment 更改数据后如何刷新 ListView?
【发布时间】:2013-05-01 15:28:16
【问题描述】:

我使用 DialogFragment 创建了一个自定义对话框,在该对话框中,我可以将一些数据添加到 SQLite 数据库。另外,在主活动中有一个列表视图,显示了 SQLite 的数据。

当我从对话框将数据添加到数据库时,我想刷新列表视图。但是,我有一些问题。

我在 onResume() 中调用 notifyDataSetChanged(),但是当我关闭对话框时列表视图不会刷新。如果我按下主页按钮并从最近列表中打开活动,列表视图将刷新。

@Override
protected void onResume() {
    super.onResume();
    listItem.clear();
    ServerListDB db = new ServerListDB(context);
    Cursor cursor = db.select();
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("serverName", String.valueOf(cursor.getString(1)));
        map.put("serverIp", cursor.getString(2));
        map.put("serverPort", cursor.getString(3));
        listItem.add(map);
    }
    notifyDataSetChanged();
}

我在 onPause() 中添加 log.v,当对话框显示时,不会调用 onPause()。这适用于 DialogFragment 吗?

@Override
protected void onPause() {
    super.onPause();
    Log.v("Pause", "onPause() called!");
}

【问题讨论】:

  • 是否甚至调用了 onResume,你检查过吗?
  • 对话框关闭时不会调用onResume,但如果我在最近的应用列表中选择活动会调用它

标签: android listview dialog dialogfragment


【解决方案1】:

您的对话框片段将与活动相关联。 一种简单的方法是直接从对话框通知您的父活动,如下所述:

http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

基于此,我将创建Activity 必须实现的Interface,以便在更新数据库时获取回调并重新加载列表(或其他):

public interface OnDBUpdatedListener {
    public void OnDBUpdated();
}

在您的活动中,您实现此接口:

public void OnDBUpdated() {
    // Reload list here
}

在您的对话框片段中,当您保存数据或关闭对话框时,输入以下代码:

(OnDBUpdatedListener)getActivity()).OnDBUpdated()

【讨论】:

  • 我的对话框是自定义对话框扩展了DialogFragment,这不起作用。
  • 对不起,我错了,我错过了你所说的 DialogFragment。
  • 谢谢,但我使用了另一个活动而不是对话框来满足我的要求,稍后我会尝试你的方法。无论如何,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多