Reputation: 1137
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);
But if I add button with width and height params it works, but there are no more margins:
secretCodeFields.addView(b,90,90);
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.
Upvotes: 1
Views: 1214
Reputation: 181
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.
Upvotes: 1