1

在此处输入图像描述
我创建了警报对话框(底部带有复选框),并在单击首选项时启动它。第一次成功启动警报对话框,但第二次出现以下异常:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.  

MainActivity.java

final View checkBoxView = View.inflate(this, R.layout.checkbox, null);   /*to inflate dialog with checkbox */
CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        System.out.println("******** CheckBox Clicked *********");
        /* Save to shared preferences */
    }
});
checkBox.setText("Use by default for this action");

Preference pref = (Preference) findPreference("preference");
        pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference arg0) {
                final CharSequence[] items = {"BT Smart Settings by ABC",
                        "BT Smart Settings by XYZ",
                        "BT Smart Settings by DEFAULT"};

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Complete action using");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        System.out.println("************* clicked-item :"+item);

                    }
                });
                builder.setView(checkBoxView);
                AlertDialog alert = builder.create();
                alert.show();
                return false;
            }
        });

在这方面的任何帮助将不胜感激。

4

2 回答 2

0

这将帮助你-:

if(checkBoxView.getParent() == null) {
 builder.setView(checkBoxView);
} else {
 checkBoxView = null; //set your view to null then set the required values again
final View checkBoxView = View.inflate(this, R.layout.checkbox, null);   /*to inflate dialog with checkbox */
CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        System.out.println("******** CheckBox Clicked *********");
        /* Save to shared preferences */
    }
});
checkBox.setText("Use by default for this action");
builder.setView(checkBoxView);

}
于 2013-01-11T16:55:22.427 回答
0

一旦你完成它,你需要打电话alert.dismiss()给你。AlertDialog

于 2012-08-20T12:31:35.207 回答