DialogFragment - retaining listener after screen rotation

人盡茶涼 提交于 2019-11-28 16:42:31

However, how am I supposed to set the listener?

You update the listener reference in the onCreate method of the Activity:

private OnDateSetListener mOds = new OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
             // do important stuff
    }
};

and in the onCreate method:

if (savedInstanceState != null) {
    DatePickerFragment dpf = (DatePickerFragment) getSupportFragmentManager()
            .findFragmentByTag("theTag?");
    if (dpf != null) {
        dpf.setListener(mOds);
    }
}

In my opinion there is a more efficient way of doing this, using the Fragment lifecycle. You can use the Fragment lifecycle callbacks onAttach() and onDetach() to automatically cast the activity as a Listener like so:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        _listener = (OnDateSetListener)activity;
    } catch(ClassCastException e) {
        // check if _listener is null before using,
        // or throw new ClassCastException("hosting activity must implement OnDateSetListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    _listener = null;
}

This technique is officially documented here

The answer of Luksprog is correct, I just want to point out, the key of the solution is the findFragmentByTag() function. Because the activity will be also recreated after screen rotation, you cannot call the setter function of its member Fragment variable, instead you should find the old fragment instance with this function.

Btw, the tag is the second parameter when you call DialogFragment.show().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!