Search code examples
androidlayout

Custom ViewGroup extending ConstraintLayout doesn't show views when the view isn't constraint to 4 sides


I've created a custom ViewGroup that extends ConstraintLayout and dynamically adds itself as a view. Inside this ViewGroup, I’m adding EditText and TextView elements. My goal is for the first EditText to be constrained on three sides: top, bottom, and start. The following views should be placed to the right, starting from the end of the previous view.

However, I'm encountering two issues:

  1. The EditText does not display unless it's constrained on all four sides, which is not what I intend. I only want it constrained on three sides.
  2. The view is occupying the entire layout even though both width and height are set to wrap_content.

What might be causing these issues, and how can I achieve the desired layout behavior?

Code for the EditText:

EditText editText = new EditText(this.context);
editText.setId(generateViewId());
editText.setLayoutParams(this.layoutParams);
editText.setMinWidth(convertDpToPx(20));
editText.setMinHeight(convertDpToPx(20));
editText.setTextSize(regularTextSizeSP);
editText.setTextColor(textColorID);
editText.setTypeface(typeFace);
editText.setBackground(null);
editText.setText(expression);
editText.setShowSoftInputOnFocus(false);
editText.setIncludeFontPadding(false);
editText.setPadding(0, 0, 0, 0);
editText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
editText.setMovementMethod(null);
editText.setFocusableInTouchMode(true);

addViewToConstraint(editText);

The addViewToConstraint method:

constraintSet = new ConstraintSet();
constraintSet.clone(this);

constraintSet.connect(view.getId(), ConstraintSet.START, this.getId(), ConstraintSet.START);
// constraintSet.connect(view.getId(), ConstraintSet.END, this.getId(), ConstraintSet.END);
constraintSet.connect(view.getId(), ConstraintSet.TOP, this.getId(), ConstraintSet.TOP);
constraintSet.connect(view.getId(), ConstraintSet.BOTTOM, this.getId(), ConstraintSet.BOTTOM);
constraintSet.applyTo(this);

Solution

  • The right approach to add view in a ConstraintLayout programmatically is:

    1. addView()
    2. constraintSet.clone()
    3. constraintSet.connect()
    4. constraintSet.applyTo()

    Use this order for adding a view programmatically in a constraintLayout