您必须首先使用AlertView在子级的父级上调用removeView()

我有一个警告对话框,我将使用TextView获取文本但是当我第二次调用它时,应用程序崩溃并出现错误:

04-15 19:37:48.433: E/AndroidRuntime(907): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

我的Java源码:

 public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.relativeLayout); Button btn1 = (Button) findViewById(R.id.button1); final AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this); build.setTitle("Ders Adı Giriniz"); final EditText dersAdiGir = new EditText(MainActivity.this); build.setView(dersAdiGir); final LinearLayout layoutDers = (LinearLayout) findViewById(R.id.layoutDers); build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Editable girilenDers = dersAdiGir.getText(); TextView tv1 = new TextView(MainActivity.this); tv1.setText(girilenDers); layoutDers.addView(tv1); dialog.dismiss(); build.create(); } }); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog alert = build.create(); alert.show(); } }); } } 

请帮帮我,谢谢大家

您每按一次按钮就会创建一个AlertDialog的新实例。 在OnClickListener内部类之外创建最终的AlertDialog

这是修复:

  final AlertDialog alert = build.create(); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alert.show(); } });