问题
In Constraint Layout, how to convert the xml attribute:
app:layout_constrainedWidth=”true|false”
in code?
回答1:
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.
I.e.
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) myView.getLayoutParams(); // View for which we need to set constrainedWidth.
lp.constrainedWidth = true/false;
myView.setLayoutParams(lp);
constrainedWidth
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.
回答2:
I just figured this out.
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)
来源:https://stackoverflow.com/questions/54230446/how-to-set-the-xml-attribute-layout-constrainedwidth-of-constraintlayout-progr