alertdialog - removeView has to get called

ぐ巨炮叔叔 提交于 2019-12-11 08:17:31

问题


I have a alert dialog with a editText area. When I call it a second time, the app crashes with error:

02-28 23:25:08.958: E/AndroidRuntime(11533): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

Here is my code:

alert = new AlertDialog.Builder(this);

    String txt_title = context.getResources().getString(R.string.txt_head_search_coord);
    String txt_message = context.getResources().getString(R.string.txt_mess_search_coord);
    alert.setTitle(txt_title);
    alert.setMessage(txt_message);

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    alert.setView(input);

    alert.setPositiveButton(context.getResources().getString(R.string.Accept), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString();

            // Do something with value!

            dialog.dismiss();
        }
    });

    alert.setNegativeButton(context.getResources().getString(R.string.Cancel), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
        }
    });

    //UTM Koordinate suchen
    btn_search_coord.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
        {
            alert.show();
        }
    });

the alert is defined globally so I can call it in the onClickListener

I'm already dismissing my dialog...


回答1:


AlertDialog.Builder.show create a new instance of Alert from the content of the Builder, including the view given in setView.

Therefore, your input will be added to both the alerts. To prevent this, use create to create a final instance of your AlertDialog and call show on this one:

final AlertDialog alertDialog = alert.create();

[...]
// in onClick
alertDialog.show();

On a broader perspective, you should use showDialog(int id) and the associated methods onCreateDialog and onPrepareDialog. However, all this is now deprecated if you use Fragments, in which case you should use a DialogFragment



来源:https://stackoverflow.com/questions/22107128/alertdialog-removeview-has-to-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!