首页 > 解决方案 > 以编程方式设置百分比宽度约束布局Android

问题描述

对于 Android 中的约束布局 v1.1.x,我们可以将高度和宽度设置为百分比。同样,需要在 Android 中以编程方式将视图宽度和高度设置为百分比:例如,这段代码是用 xml 编写的,用于一些约束布局:

<!-- the widget will take 40% of the available space -->
    app:layout_constraintWidth_default="percent"
    app:layout_constraintWidth_percent="0.4"

它运行时的java代码是什么?

标签: javaandroidandroid-constraintlayout

解决方案


您需要使用 ConstraintSet -参考

此类允许您以编程方式定义一组要与 ConstraintLayout 一起使用的约束。它允许您创建和保存约束,并将它们应用到现有的 ConstraintLayout。ConstraintsSet 可以通过多种方式创建:

mConstraintLayout = (ConstraintLayout) findViewById(R.id.myconstraint_layout)

ConstraintSet set = new ConstraintSet();

// Add constrains - Here R.id.myconstraint_layout is the Id of your constraint layout
set.constrainPercentHeight(R.id.myconstraint_layout, 0.4);
set.constrainPercentWidth(R.id.myconstraint_layout, 0.4);

// Apply the changes - mConstraintLayout is reference to the desired view
set.applyTo(mConstraintLayout); 

您可以在此集合上调用那些高度宽度百分比方法

并像这样将这些约束应用于您的约束布局

set.applyTo(mConstraintLayout); 

推荐阅读