无法将DialogFragment添加到Dialog

时间:2014-03-07 00:11:10

标签: android android-fragments android-dialogfragment

我之前尝试过多个解决方案,但没有一个适用于我的情况。我的活动启动一个非UI片段,然后显示一个对话框片段。我正在使用setTargetFragment在片段和dialogfragment之间进行通信。但我一直在收到错误:

  

java.lang.IllegalStateException:指定的子节点已经有了   家长。您必须首先在孩子的父母身上调用removeView()。

我的代码:(我正在为所有片段/活动使用支持库)

活动:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment f1 = F1.newInstance();
ft.replace(R.id.container, f1, "f1");   //I have previously shown a fragment in this activity, so replacing
ft.commit();


Fragment (F1):


 public static F1 newInstance() {
            F1 f = new StartupOptionalServicesFragment();
            f.setRetainInstance(true);
            return f;
        }


@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DialogFragment d1 = D1.newInstance();
        d1.setTargetFragment(this, 0);
        d1.show(getActivity().getSupportFragmentManager(), "d1");

    }

DialogFragment(D1)

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        builder = new AutoScrollAlertDialogBuilder(getActivity());
    } else {
        builder = new AutoScrollAlertDialogBuilder(getActivity(), AlertDialog.THEME_HOLO_DARK);
    }

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    final View view = inflater.inflate(R.layout.dialog_d1, null, false);

    TextView message = (TextView) view.findViewById(R.id.mytitle);
    message.setText("Agree ?");

    builder.setView(view).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, int whichButton) {

            callback = (D1Callback)getTargetFragment();
            if (callback != null) callback.selection(true);
            dialog.dismiss();
        }
    });

    builder.setView(view).setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialog, int whichButton) {

            callback = (D1Callback)getTargetFragment();
            if (callback != null) callback.selection(false);
            dialog.dismiss();
        }
    });

    Dialog dialog = builder.create();
    return dialog;

}

0 个答案:

没有答案