添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
玩手机的鸡蛋面  ·  Linux — ...·  11 月前    · 
沉着的热水瓶  ·  Assets, Resources and ...·  1 年前    · 
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

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

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)
                Thank you! This was driving me bananas, but constrainDefaultWidth did the trick for a progammatically created and constrained views.
– Barn on a Hill
                Oct 4, 2019 at 17:25
        

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.