您必须首先使用 AlertView 在 child 的 parent 上调用 removeView()

You must call removeView() on the child's parent first with AlertView

我有一个警告对话框,我将使用 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 内部 class 之外创建最终 AlertDialog

修复方法如下:

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