Fragment null必须是要从实例状态正确重新创建的公共静态类 [英] Fragment null must be a public static class to be properly recreated from instance state
问题描述
我无法弄清楚为什么我的应用程序在调用getSupportFragmentManager()时崩溃。我在其他应用程序中使用了类似的代码来创建警告对话框而没有任何问题。请帮助!
I am not able to figure out why my app crashes when getSupportFragmentManager() is called.I have used similar code in other apps to create alert dialogs without any issues.please help!
DialogFragment df = new DialogFragment(){
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.addincome,null);
builder.setView(view);
//capture
final EditText amountEditText=(EditText)view.findViewById(R.id.edit_amount);
final EditText descriptionEditText=(EditText)view.findViewById(R.id.edit_description);
builder.setNegativeButton(android.R.string.cancel,null);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
newIncome.setAmount(Double.parseDouble(amountEditText.getText().toString()));
newIncome.setDescription(descriptionEditText.getText().toString());
user.incomes.add(newIncome);
HashMap<String,User> modified = new HashMap<>();
modified.put(uid,user);
rootref.setValue(modified);
}
});
return builder.create();
}
};
df.show(getSupportFragmentManager(),"addIncome");
推荐答案
您的 DialogFragment
是一个匿名类,在Java中,匿名类只能由父类实例化: new DialogFragment()
实际上是这个.new DialogFragment()
。显然,当 FragmentManager
尝试在配置更改时重新创建 DialogFragment
时,它不能,因为它不会可以访问父类的实例。解决方案是声明 static
DialogFragment
的子类,或声明<$的顶级子类c $ c> DialogFragment ,并使用它而不是匿名类。
Your DialogFragment
is an anonymous class, and in Java anonymous classes can only be instantiated by parent classes: the new DialogFragment()
is in fact this.new DialogFragment()
. Apparently, when FragmentManager
tries to recreate your DialogFragment
upon a configuration change, it can't, since it doesn't have the access to the instance of the parent class. The solution would be to either declare a static
subclass of DialogFragment
, or to declare a top-level subclass of DialogFragment
, and use it instead of the anonymous class.
这篇关于Fragment null必须是要从实例状态正确重新创建的公共静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!