How to set the XML attribute 'layout_constrainedWidth' of ConstraintLayout programmatically?

谁都会走 提交于 2019-12-12 17:25:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!