以编程方式设置Android的宽度约束百分比布局

ghu*_*nne 3 java android android-constraintlayout

对于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"
Run Code Online (Sandbox Code Playgroud)

在运行时执行它的Java代码是什么?

Ben*_*aci 11

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

科特林:

(myView.layoutParams as ConstraintLayout.LayoutParams)
    .matchConstraintPercentWidth = value
myView.requestLayout()
Run Code Online (Sandbox Code Playgroud)

爪哇:

(myView.layoutParams (ConstraintLayout.LayoutParams))
    .matchConstraintPercentWidth = value
myView.requestLayout()
Run Code Online (Sandbox Code Playgroud)


adi*_*e49 7

您需要使用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); 
Run Code Online (Sandbox Code Playgroud)

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

并将这些约束应用于您的约束布局,如下所示

set.applyTo(mConstraintLayout); 
Run Code Online (Sandbox Code Playgroud)


小智 6

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

// 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);
Run Code Online (Sandbox Code Playgroud)

请注意,出于某种原因,1.0F 的百分比约束不起作用,尽管 0.99F 工作得很好。

  • 这必须被接受的答案,没有克隆,现有的约束将丢失 (2认同)