1

This is my code:

ConstraintLayout.LayoutParams buttonParams = new ConstraintLayout.LayoutParams(40,105);
buttonParams.setMargins(8,16,24,32);
secretCodeFields = findViewById(R.id.secretCodeFields);
for (int i = 0; i < 4; i++) {
    Button b = new Button(this);
    vID[i]=View.generateViewId();
    b.setId(vID[i]);
    b.setLayoutParams(buttonParams);

    secretCodeFields.addView(b);
}
set.clone(secretCodeFields);
set.createHorizontalChain(
    secretCodeFields.getId(),ConstraintSet.LEFT,
    secretCodeFields.getId(),ConstraintSet.RIGHT,
    vID,null,ConstraintSet.CHAIN_PACKED
    );
set.applyTo(secretCodeFields);

Buttons are added in the same place (so only last one is visible). The same resultat if I delete "b.setLayoutParams(buttonParams);" line and use

secretCodeFields.addView(b,buttonParams);

All buttons in one place

But if I add button with width and height params it works, but there are no more margins:

secretCodeFields.addView(b,90,90);

Buttons in chain but without margins

What I do wrong?

EDIT: secretCodeFields is ConstraintLayout

I found solution. I added margins AFTER set.applyTo... :

for (int i = 0; i < codeLenght; i++) {
        Button b = (Button)findViewById(vID[i]);
        ConstraintLayout.LayoutParams p = (ConstraintLayout.LayoutParams) b.getLayoutParams();
        p.setMargins(6,0,6,0);
        b.setLayoutParams(p);
    }

It works, but I don't know if it is the best solution.

Patryk Godowski
  • 1,081
  • 7
  • 7
  • Why don't you try `ConstraintSet.PARENT_ID` instead of `view.getId()`? – Gabriel Costin Jan 16 '19 at 10:44
  • I think that it's the same in this case. I changed this for "set.createHorizontalChain( ConstraintSet.PARENT_ID,ConstraintSet.LEFT, ConstraintSet.PARENT_ID,ConstraintSet.RIGHT, vID,null,ConstraintSet.CHAIN_PACKED ); ", but the resultat is the same. – Patryk Godowski Jan 16 '19 at 11:35
  • What type of view is secretCodeFields? – Charan M Jan 16 '19 at 12:48
  • secretCodeFields is ConstraintLayout – Patryk Godowski Jan 16 '19 at 13:04
  • I had a problem also when I used chain in `ConstraintLayout` that Id's of view's were not in correct format but I see you already use `generateViewId()` method which solved my problem, so I don't really know, maybe do some debugging and see what happens when you create that chain – Gabriel Costin Jan 16 '19 at 16:12

1 Answers1

1

I know this is a late answer but here it is

the ConstraintSet.CHAIN_PACKED will remove all applied margins to your views you should first create the chain in Constraint Set then after that apply margins using the ConstrainSet connect(int startID, int startSide, int endID, int endSide, int margin) method to indicate margins.

ErfanDP
  • 171
  • 5