我已经关注并定制了一些关于 DialogFragments 的 Android 教程,这就是我编写的代码:
public class ChooseDialog extends DialogFragment {
ArrayList mSelectedItems;
CharSequence[] items;
boolean[] selected;
public static ChooseDialog newInstance(CharSequence[] options) {
ChooseDialog f = new ChooseDialog();
Bundle args = new Bundle();
args.putCharSequenceArray("items", options);
f.setArguments(args);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose")
.setMultiChoiceItems(savedInstanceState.getCharSequenceArray("items"), null,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
if (isChecked) {
mSelectedItems.add(whichButton);
} else if (mSelectedItems.contains(whichButton)) {
mSelectedItems.remove(Integer.valueOf(whichButton));
}
}
})
.setPositiveButton("Chosen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
}
我调用活动,我想在其中显示我的对话框:
CharSequence items[] = { "foo", "bar" };
DialogFragment newFragment = ChooseDialog.newInstance(items);
newFragment.show(this.getFragmentManager(), "somedialog");
它在调用 setMultiChoiceItems 时崩溃,因为 Bundle savedInstanceState 为空。我应该怎么办?也许它可以做得更优雅,因为我刚刚开始学习 Android 开发.. :)