如何在使用DialogFragment更改数据后刷新ListView?

时间:2013-05-01 15:28:16

标签: android listview dialog dialogfragment

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

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

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

@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!");
}

1 个答案:

答案 0 :(得分:0)

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

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

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

public interface OnDBUpdatedListener {
    public void OnDBUpdated();
}

在您的活动中,您实现了此界面:

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

在对话框片段中,当您保存数据或解除对话框时,请输入以下代码:

(OnDBUpdatedListener)getActivity()).OnDBUpdated()
相关问题