how to MODIFY a constraint layout programmatically?
If you are using Kotlin and you have androidx-core-ktx lib you can simply do:
someView.updateLayoutParams<ConstraintLayout.LayoutParams> { horizontalBias = 0.5f }
I just found the answer in here and you can use ConstraintSet
to achieve this like below:
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(context, R.id.activity_constraint);
//for example lets change the vertical bias of tvDownVoteIcon
float biasedValue = 0.2f;
constraintSet.setVerticalBias(R.id.tvDownVoteIcon, biasedValue);
//or change the anchor
constraintSet.connect
(R.id.tvDownVoteIcon,ConstraintSet.RIGHT,R.id.txt,ConstraintSet.RIGHT,0);
//then apply
constraintSet.applyTo( (ConstraintLayout) findViewById(R.id.activity_constraint));
Here is what I did (no need for ConstraintSet
, we can work directly on the constraints themselves):
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) myView.getLayoutParams();
params.horizontalBias = 0.2f; // here is one modification for example. modify anything else you want :)
myView.setLayoutParams(params); // request the view to use the new modified params
it worked like a charm when I had a SeekBar
and a TextView
below it (aligned to it both left+right), and I wanted to update the TextView
position to be under the SeekBar
's cursor, so I had to update the horizontal bias params on the SeekBar
's OnSeekBarChangeListener