繁体   English   中英

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

此类允许您以编程方式定义一组要与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); 

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

科特林:

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

爪哇:

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

我发现上面的答案很有帮助,但仍然有点令人困惑。 这就是最终对我有用的东西。 本例中涉及到 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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM