mat*_*ttm 6 java android bundle dialogfragment
我正在尝试使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我通过这种方式从一个活动中调用它:
SampleDialog myDialog = SampleDialog.newInstance("does not appear");
FragmentTransaction transaction = getFragmentManager().beginTransaction();
myDialog.show(transaction, TAG);
Run Code Online (Sandbox Code Playgroud)
Bla*_*elt 16
你必须用来getArguments检索Bundle你设置的setArguments
代替
if(savedInstanceState != null) {
dialogMessage = savedInstanceState.getString(DIALOG_MESSAGE);
}
Run Code Online (Sandbox Code Playgroud)
你应该有类似的东西:
Bundle bundle = getArguments();
if (bundle != null) {
dialogMessage = bundle.getString(DIALOG_MESSAGE);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5585 次 |
| 最近记录: |