alertdialog-必须调用removeView [英] alertdialog - removeView has to get called
问题描述
我有一个带有editText区域的警报对话框.当我第二次调用它时,该应用程序崩溃并显示错误:
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.
这是我的代码:
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();
}
});
警报是全局定义的,因此我可以在onClickListener中调用
the alert is defined globally so I can call it in the onClickListener
我已经关闭了我的对话框...
I'm already dismissing my dialog...
推荐答案
AlertDialog.Builder.show
从Builder
的内容(包括在setView
.
因此,您的input
将同时添加到alerts
中.为防止这种情况,请使用create
创建AlertDialog
的最终实例,并在该实例上调用show
:
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();
从更广泛的角度来看,应该使用showDialog(int id)
以及关联的方法onCreateDialog
和onPrepareDialog
.但是,如果您使用Fragments
,则现在不建议使用所有这些,在这种情况下,您应该使用DialogFragment
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
这篇关于alertdialog-必须调用removeView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!