Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
In Constraint Layout, how to convert the xml attribute:
app:layout_constrainedWidth=”true|false”
in code?
If you want to set
constrainedWidth/Height
programatically, then you've to take
ConstraintLayout.LayoutParams
for your view and set the flag named
constrainedWidth
or
constrainedHeight
at your will.
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) myView.getLayoutParams(); // View for which we need to set constrainedWidth.
lp.constrainedWidth = true/false;
myView.setLayoutParams(lp);
Specify if the horizontal dimension is constrained in case both left &
right constraints are set and the widget dimension is not a fixed
dimension.
By default, if a widget is set to WRAP_CONTENT
, we will
treat that dimension as a fixed dimension, meaning the dimension will
not change regardless of constraints.
Setting this attribute to true
allows the dimension to change in order to respect constraints.
Check out here.
So base on the answers above,
constrainedWidth
can be accessed through ConstraintLayout.LayoutParams
and thus can be altered by the following code: (Thank you @JeelVankhede)
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams)
myView.getLayoutParams(); // View for which we need to set constrainedWidth.
lp.constrainedWidth = true/false;
myView.setLayoutParams(lp);
However when using ConstraintsSet
the following code would be needed:
val constraintLayout = // your constraint layout
val constraintSet = ConstraintSet()
constraintSet.clone(constraintLayout)
// This is the imporatant part
constraint.constrainDefaultWidth(R.id.yourViewId, ConstraintSet.MATCH_CONSTRAINT_WRAP)
constraintSet.applyTo(constraintLayout)
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.