我的自定义DialogFragment不会显示在活动中

时间:2013-09-13 13:54:25

标签: android

我已经关注并定制了一些关于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为null。我该怎么办?也许它可以做得更优雅,因为我刚刚开始学习Android开发.. :)

2 个答案:

答案 0 :(得分: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);
        }
    });

的ShowDialog

    public void showDialog(View v) {
    DialogFragment fragment1 = new CopyOfTimePickerFragment1();
    fragment1.show(getFragmentManager(), "");
}

答案 1 :(得分:0)

savedInstanceState包不是存储参数的地方。

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

所以

savedInstanceState.getCharSequenceArray("items")

变为

getArguments().getCharSequenceArray("items")