0

我已经关注并定制了一些关于 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 开发.. :)

4

2 回答 2

1

这对我有用。

public class DialogFragment1 extends DialogFragment{

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    final Dialog dialog = new Dialog(getActivity());
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    dialog.setContentView(R.layout.your_layout);
    dialog.getWindow().setBackgroundDrawable(
            new ColorDrawable(Color.TRANSPARENT));
    dialog.show();
    return dialog;
}
}

并且在活动中

tv.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            showDialog(v);
        }
    });

显示对话框

    public void showDialog(View v) {
    DialogFragment fragment1 = new CopyOfTimePickerFragment1();
    fragment1.show(getFragmentManager(), "");
}
于 2013-09-13T14:26:28.520 回答
0

savedInstanceState 包不是存储参数的位置。

您需要的捆绑包来自 getArguments();

所以

savedInstanceState.getCharSequenceArray("items")

变成

getArguments().getCharSequenceArray("items")
于 2013-09-13T13:57:03.377 回答