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

时间:2015-04-15 21:11:48

标签: java android android-edittext android-alertdialog

我有一个警告对话框,我将使用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();
            }
        });




    }
}

请帮助我,谢谢所有

1 个答案:

答案 0 :(得分:12)

您每次点击按钮都会创建AlertDialog的新实例。在AlertDialog内部类之外创建最终OnClickListener

以下是修复:

        final AlertDialog alert = build.create();

        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                alert.show();
            }
        });