第二次启动Alert Dialog时出现java.lang.IllegalStateException

时间:2012-08-20 12:23:21

标签: android android-preferences android-alertdialog

enter image description here
        我创建了警报对话框(底部带有复选框),并在单击“首选项”时启动它。第一次警报对话框成功启动,但第二次出现异常后:

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;
            }
        });

在这方面的任何帮助都将受到赞赏。

2 个答案:

答案 0 :(得分:0)

完成后,您需要在alert.dismiss()上致电AlertDialog

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

}