setLayoutParams on ConstraintLayout (SLPCL)

I have 2 text views, one above the other:

XXXXXXXXXXXX[TextView1]
XXXXXXXXXXXX[TextView2]
  • Both TextViews are aligned to the right. (Hence the XXX above)
  • TextView1 has a background color.
  • TextView2 is always longer than TextView1
  • The left of TextView1 should be aligned with TextView2

I have the above 4 requirements. Now everything works fine using ConstraintLayout, where the left of TextView1 is constrained to the left of TextView2, and the width of TextView2 is wrap_content.

But now comes the 5th requirement:

  • TextView2 can disappear, leaving TextView1.

setVisibility(GONE) doesn't work, because TextView2 must be  wrap_content. it will be 0 width and therefore TextView1 too (because its left is constrained to the left of TextView2)

Then I tried to set the height of TextView2 to 0, using the code below:

   ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams)textView2.getLayoutParams();
    lp.width = widthInPixelOrConstant;
    textView2.setLayoutParams(lp);

Oops, nothing happened. TextView2 just stayed there, as if nothing happened. I googled for half an hour, and finally decided to wrap TextView2 in a LinearLayout file.

And then use the code below to set the height of TextView2 to 0:

LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams )view.getLayoutParams();
lp.width = widthInPixelOrConstant;
view.setLayoutParams(lp);

So, it turns out, we can't use what we used before - setLayoutParams to try to change the height or width of a ConstraintLayout child at runtime.

But then, wrapping that TextView2 in a LinearLayout is just plain stupid. Does anyone know how to change the width or height of a ConstraintLayout child at runtime?

Solutip

Try adding constraints at runtime, like this:

//Define some variables
TextView textView1;
TextView textView2;
ConstraintLayout constraintLayout;

//Initialize them, and so some stuff
textView1 = (TextView) findViewById(R.id.text1);
textView2 = (TextView) findViewById(R.id.text2);
constraintLayout = (ConstraintLayout) findViewById(R.id.constraintLayout);

int x = 200; //set some width
int y = 200; //Set some height        

ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT);

lp.width = x;
lp.height = y;

//moves TextView1's left to align with TextView2's left
lp.editorAbsoluteX = ((int) textView2.getX());     

textView1.setLayoutParams(lp);

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

constraintSet.connect(R.id.text1,ConstraintSet.LEFT,R.id.text2,ConstraintSet.LEFT,0);
constraintSet.connect(R.id.text2,ConstraintSet.TOP,R.id.text1,ConstraintSet.BOTTOM,0);

constraintSet.applyTo(constraintLayout);

Post a Comment

Previous Next

نموذج الاتصال