![](/img/trans.png)
[英]Dialogfragment onCreateDialog NullPointerException
[英]While passing Android DialogFragment arguments, onCreateDialog bundle agument is unexpectedly null
我正在尝试使用DialogFragment在Android中显示一个基本对话框,使用对话框消息的参数,如StackOverflow线程和DialogFragment文档中所述 。 我的问题是onCreateDialog中的Bundle参数savedInstanceState始终显示为null,这意味着该活动显示一个空对话框而不是带有消息的对话框。 如何从newInstance工厂方法获取非null的bundle内容以显示在onCreateDialog中? 或者我只是遗漏了别的东西?
我从文档中看到的唯一重要区别是我使用的是非静态类。 我希望积极的对话框按钮取决于消息的内容,所以这是故意的。
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
public class SampleDialog extends DialogFragment {
public static final String DIALOG_MESSAGE = "dialogMessage";
private String dialogMessage;
// arguments are handled through factory method with bundles for lifecycle maintenance
public SampleDialog(){
}
public static SampleDialog newInstance(String dialogMessage){
SampleDialog fragment = new SampleDialog();
Bundle args = new Bundle();
args.putString(DIALOG_MESSAGE, dialogMessage);
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if(savedInstanceState != null) {
dialogMessage = savedInstanceState.getString(DIALOG_MESSAGE);
}
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(dialogMessage)
.setPositiveButton(R.string.dial, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// will depend on content of dialogMessage
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
我通过这种方式从一个活动中调用它:
SampleDialog myDialog = SampleDialog.newInstance("does not appear");
FragmentTransaction transaction = getFragmentManager().beginTransaction();
myDialog.show(transaction, TAG);
你必须使用getArguments
检索Bundle
你设置setArguments
代替
if(savedInstanceState != null) {
dialogMessage = savedInstanceState.getString(DIALOG_MESSAGE);
}
你应该有类似的东西:
Bundle bundle = getArguments();
if (bundle != null) {
dialogMessage = bundle.getString(DIALOG_MESSAGE);
}
我有同样的问题,你必须使用getArguments
,正如getArguments
所说。
当调用onSaveInstanceState
( 文档 )时, savedInstanceState
将可用,并且某些数据将在outState
填充,以便在后面检索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.