Search code examples
androidandroid-edittextandroid-constraintlayout

Why does my app crash when I click the floating action button?


My app crash when I am clicking the button, I don't know why it does that and I don't know how to fix it.

fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
            mLayout.addView(createNewEditText(mEditText.getText().toString()));
        }
    });

private EditText createNewEditText(String text) {
    ConstraintLayout mConstraintLayout  = (ConstraintLayout) findViewById(R.id.planlaeg_l);
    ConstraintSet set = new ConstraintSet();
    EditText et = new EditText(this);
    mConstraintLayout.addView(et,0);
    set.clone(mConstraintLayout);
    set.connect(et.getId(), ConstraintSet.TOP, mConstraintLayout.getId(), ConstraintSet.TOP, 60);
    set.applyTo(mConstraintLayout);
    et.setText(text);
    return et;
}

Solution

  • I think you got an error like that "java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."

    • Step 1:

      mConstraintLayout.addView(et,0);

    • Step 2:

      return et;

    • Step 3:

      mLayout.addView(createNewEditText(mEditText.getText().toString()));

    How to fix it:

    • Change logic add et view (in method createNewEditText / outside it)

    Example:

    fab.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View view) {
                createNewEditText(mEditText.getText().toString());
            }
        });