我目前遇到了DialogFragments的一些问题。 我正在使用最新的v.4支持包(我相信是第8版)。 我的问题是,如果我的手机在对话框打开时改变方向,应用程序会开始表现出奇怪的行为。
目前我的应用程序的工作方式如下: 有一个FragmentActivity,它调用一个Fragment。 然后,该Fragment通过getActivity().getSupportFragmentManager()调用一个DialogFragment。
如果方向在对话框打开时发生变化,则Fragment中的getActivity() = null。 如果我想结束Activity等操作,这会导致问题。
要引起此问题,您需要打开对话框,更改方向并按下按钮。只有在按下按钮后才会崩溃。
我的DialogFragment称为AlertDialogFragment:
public class AlertDialogFragment extends DialogFragment {
private static Builder mBuilder;
private static DialogInterface.OnClickListener mListener;
public static AlertDialogFragment newInstance(Context context, DialogInterface.OnClickListener listener) {
mBuilder = new AlertDialog.Builder(context);
mListener = listener;
return new AlertDialogFragment();
}
//... some functions to set Icons etc
public void setButton(int whichButton, CharSequence buttonText) {
final DialogInterface.OnClickListener listener = mListener == null ? null : mListener;
mBuilder.setPositiveButton(buttonText, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
listener.onClick(dialog, whichButton);
}
});
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mBuilder.create();
}
}
这是代码片段:
public class TestBedFragment extends Fragment implements DialogInterface.OnClickListener {
// onCreateView Stuff
private void showCrashDialog() {
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
AlertDialogFragment newDialog = AlertDialogFragment.newInstance(getActivity(), this);
newDialog.setTitle("Test");
newDialog.setIcon(android.R.drawable.ic_dialog_alert);
newDialog.setMessage("Testing testing testing... 1, 2, 3... Just press Ok.");
newDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok");
newDialog.show(ft, "dialog");
// Cause the problem. Simulate the user turning the screen
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
@Override
public void onClick(DialogInterface dialog, int which) {
/*
* hexnumber = a hex number
* Normally equals: TestBedFragment{hexnumber #0 id=hexnumber}
* With crash equals: TestBedFragment{hexnumber}
*/
Log.e("TestBedFragment", "this = " + this);
/*
* hexnumber = a hex number
* Normally equals: com.example.TestBed.TestBedActivity@hexnumber
* With crash equals: null
*/
Log.e("TestBedFragment", "getActivity() = " + getActivity()); // Will equal null... ???
getActivity().finish();
}
}
我不太确定是什么导致了这个问题?如果这是一个愚蠢的问题,那我很抱歉。我在其他地方读到过关于“Window Leaking”的内容,但我在logcat中没有看到任何相关信息。
有人能帮助我吗 :) 非常感谢
谢谢