以编程方式设置百分比宽度约束布局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"

在运行时执行it的java代码是什么?

您需要使用ConstraintSet-Reference

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

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

你可以在这个集合上调用那些高度-宽度百分比方法

  • constrainPercentHeight(int viewId,浮动百分比(
  • constrainPercentWidth(int视图ID,浮动百分比(

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

set.applyTo(mConstraintLayout); 

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

科特林:

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

Java:

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

我发现上面的答案很有用,但仍然有点令人困惑。以下是最终对我有效的方法。本例涉及两个视图,一个是父约束视图,另一个是约束视图的子视图。

// 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的作用很好。

最新更新