我目前遇到了DialogFragments的一些問題。 我正在使用最新的v.4支持包(我相信第8修訂版) 我的問題是,如果在打開對話框時手機的方向發生了變化,應用程序開始變得更加奇怪。DialogFragment方向使用getActivity更改崩潰()
目前我的應用程序是這樣的: 有一個FragmentActivity,它調用一個Fragment。然後 該片段調用DialogFragment(通過getActivity()。getSupportFragmentManager()。
如果方向的變化,而對話是開放的,getActivity()的片段= NULL。 這會導致一個問題,如果我想完成活動等
導致此打開對話框,更改方向,然後按下一個按鈕,按下該按鈕後,才崩潰
我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: [email protected]
* With crash equals: null
*/
Log.e("TestBedFragment", "getActivity() = " + getActivity()); // Will equal null... ???
getActivity().finish();
}
}
我也不太清楚什麼造成的?對不起,如果它是一個愚蠢的問題。我已經在其他地方讀過'Windows Leaking',但是我還沒有在logcat中看到任何提及的東西。
誰能幫我:)它極大的讚賞
感謝