且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何刷新ListView控件后更改与DialogFragment的数据?

更新时间:2023-12-03 15:03:58

您对话片段将被捆绑到活动。
一个简单的方法是直接从对话框通知你的父活动,如下所述:

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

在此基础上,我将创建一个接口活动必须为了得到一个回调时,数据库实现更新并重新加载列表(或其他):

 公共接口OnDBUpdatedListener {
    公共无效OnDBUpdated();
}

在你的活动()你实现这个接口:

 公共无效OnDBUpdated(){
    //刷新列表在这里
}

在您的对话片段,当保存数据,或者当你关闭对话框,把下面的code:

 (OnDBUpdatedListener)getActivity())。OnDBUpdated()

I create a custom dialog with DialogFragment, and in the dialog, I can add some data to the SQLite database. Also, there is a listview in the main activity, which show the data of the SQLite.

I want to refresh the listview when I add the data to the database from the dialog. However, I have some problems.

I call the notifyDataSetChanged() in the onResume(), but the listview doesn't refresh when I dismiss the dialog. And if I press the home button and open the activity from the recent list, the listview will refresh.

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

I add the log.v in the onPause(), and when the dialog show, the onPause() isn't called. Is this right for DialogFragment?

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

Your dialog fragment will be tied to activity. One simple approach is to notify your parent activity directly from dialog, as described here:

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

Based on this, I would create an Interface that Activity must implement in order to get a callback when database is updated and to reload a list (or whatever):

public interface OnDBUpdatedListener {
    public void OnDBUpdated();
}

In your activity(s) you implement this interface:

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

In your dialog fragment, when you save data or when you are dismissing the dialog, put the following code:

(OnDBUpdatedListener)getActivity()).OnDBUpdated()