我正在尝试使用DialogFragment在Android中显示基本对话框,使用对话框消息的参数,如StackOverflow thread和DialogFragment documentation中所述。 我的问题是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);
答案 0 :(得分:14)
您必须使用getArguments
来检索您使用Bundle
setArguments
而不是
if(savedInstanceState != null) {
dialogMessage = savedInstanceState.getString(DIALOG_MESSAGE);
}
你应该有类似的东西:
Bundle bundle = getArguments();
if (bundle != null) {
dialogMessage = bundle.getString(DIALOG_MESSAGE);
}
答案 1 :(得分:1)
我有同样的问题,你必须使用getArguments
,正如Blackbelt所说。
调用savedInstanceState
(documentation)并在onSaveInstanceState
填写一些数据后,outState
将可用,以便在后面检索。