我有一个主片段,它启动一个DialogFragment,并通过“setOnOptionClickListener(interface OnOptionClickListener)”设置一个Listener(在DialogFragment中定义的接口)。
如何将它存储在setOnOptionClickListener的onSaveInstance中?
在方向更改后,访问DialogFragment中MainFragment传递的侦听器的方法会抛出NullPointerException。
以下代码是原始版本的精简版。
在MainFragment中
private void showDialog(){
CustomDialogFragment dialog = new CustomDialogFragment();
dialog.setOnOptionClickListener(new OnOptionClickListener(){
//Overwrite some methods
});
dialog.show(getChildFragmentManager(), "optionsdialog");
}
在CustomDialogFragment中
public class CustomDialogFragment extends DialogFragment {
public interface OnOptionClickListener{
ArrayList<String> getData();
void onDone();
}
private ArrayList<String> data = new ArrayList<String>();
public void setOnOptionClickListener(OnOptionClickListener mListener){
this.mListener = mListener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
... do some stuff ...
//Accessing the Listener!
data = mListener.getData();
/* I could save the ArrayList in onSaceInstanceState Bundle Argument
But how do I save the call to the listener with the method that MainFragment
overwrote and passed as argument (setOnOptionClickListener()...) ?? */
mListener.onDone();
}
}