我正在尝试使用 DialogFragment 在 Android 中显示一个基本对话框,并使用对话框消息的参数,如中所述StackOverflow线程 https://stackoverflow.com/questions/15459209/passing-argument-to-dialogfragment and DialogFragment 文档 http://developer.android.com/reference/android/app/DialogFragment.html。
我的问题是 onCreateDialog 中的 Bundle 参数 savingInstanceState 始终显示为 null,这意味着该活动显示一个空对话框而不是带有消息的对话框。如何从 newInstance 工厂方法获取非空包内容以显示在 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)