我在activity中显示一个对话框片段,尝试使用show()和add()方法。代码如下:
HelpDialogFragment hdf = HelpDialogFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(hdf, "dialog");
ft.commit(); #crash here
我有时从上面的代码中得到IllegalStateException错误,崩溃日志在下面给出
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1329)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:548)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:532)
at com.delight.activities.HomeActivity.showHelp(HomeActivity.java:311)
行号HomeActivity.java中的311是上面代码中提到的ft.commit()
。我的活动从兼容性库(这是迄今为止的更新)扩展了FragmentActivity。如果我使用show()
方法,则会发生同样的崩溃。
HelpDialogFragment hdf = HelpDialogFragment.newInstance();
hdf.show(getSupportFragmentManager(), "dialog"); #same crash here
所以我得出的结论是getSupportFragmentManager()
给我带来了问题,我不明白的是,在代码的哪一部分,我使用的是被破坏的活动,就我而言了解getSupportFragmentManager()
应该让管理员知道现有的活动。
我需要一些帮助来解决这个问题。
答案 0 :(得分:0)
查看对话框片段你只需要调用dialogfrag.show(Fmanager,tag); 通过事务添加它会产生异常
答案 1 :(得分:0)
使用getFragmentManager而不是getSupportFragmentManager
dialog.show(getFragmentManager(), "submitting"); // The second parameter doesn't really matter.
如果这不起作用,请延伸DialogFragment来执行此操作。关键是在构建对话框时使用Activity而不是使用支持库。
dialog = new AlertDialogFragment(title, message);
dialog.show(getFragmentManager(), "submitting");
AlertDialogFragment:
public class AlertDialogFragment extends DialogFragment {
static final String TAG_TITLE = "title";
static final String TAG_MSG = "message";
public AlertDialogFragment(){
}
public AlertDialogFragment(String title, String message) {
Bundle b = new Bundle();
b.putString(TAG_TITLE, title);
b.putString(TAG_MSG, message);
setArguments(b);
}
public AlertDialogFragment newInstance(String title, String message) {
AlertDialogFragment frag = new AlertDialogFragment();
Bundle b = new Bundle();
b.putString(TAG_TITLE, title);
b.putString(TAG_MSG, message);
frag.setArguments(b);
return frag;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString(TAG_TITLE);
String message = getArguments().getString(TAG_MSG);
// Use getActivity()!
return new AlertDialog.Builder(getActivity()).setTitle(title)
.setMessage(message)
.setNegativeButton("Dismiss", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "Dialog cancel");
}
}).create();
}
@Override
public void onCancel(DialogInterface dialog) {
Log.d(TAG, "Cancel Dialog");
super.onCancel(dialog);
}
@Override
public void onDismiss(DialogInterface dialog) {
Log.d(TAG, "Dismiss Dialog");
super.onDismiss(dialog);
}
}
}
答案 2 :(得分:0)
您的类应该扩展FragmentActivity而不是Activity。这解决了我的问题