以编程方式设置百分比宽度 constraintlayout Android

set percent width constraintlayout Android programmatically

对于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 代码是什么?

您需要使用 ConstraintSet - Reference

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways:

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); 

不确定这是好是坏,但除了建议的答案之外,还有另一种方法可以做到这一点:

科特林:

(myView.layoutParams as ConstraintLayout.LayoutParams)
    .matchConstraintPercentWidth = value
myView.requestLayout()

Java:

(myView.layoutParams (ConstraintLayout.LayoutParams))
    .matchConstraintPercentWidth = value
myView.requestLayout()

我发现上面的答案很有帮助,但还是有点令人困惑。这就是最终对我有用的东西。本例涉及2个视图,一个父Constraint View和一个子Constraint View。

// Get the constraint layout of the parent constraint view.
ConstraintLayout mConstraintLayout = findViewById(R.id.parentView);

// Define a constraint set that will be used to modify the constraint layout parameters of the child.
ConstraintSet mConstraintSet = new ConstraintSet();

// Start with a copy the original constraints.
mConstraintSet.clone(mConstraintLayout);

// Define new constraints for the child (or multiple children as the case may be).
mConstraintSet.constrainPercentWidth(R.id.childView, 0.5F);
mConstraintSet.constrainPercentHeight(R.id.childView, 0.7F);

// Apply the constraints for the child view to the parent layout.
mConstraintSet.applyTo(mConstraintLayout);

请注意,由于某种原因,1.0F 的百分比约束不起作用,尽管 0.99F 可以正常工作。