在 iOS 中,我非常喜欢删除 Storyboard 并使用制图框架将所有内容放在代码中。这是从 Cartography 的 github 上偷来的:
constrain(view1, view2) { view1, view2 in
view1.width == (view1.superview!.width - 50) * 0.5
view2.width == view1.width - 50
view1.height == 40
view2.height == view1.height
view1.centerX == view1.superview!.centerX
view2.centerX == view1.centerX
view1.top >= view1.superview!.top + 20
view2.top == view1.bottom + 20
}
Android 是否有任何等价物?似乎新的约束布局是朝着正确方向迈出的一步,但我想以编程方式进行。
最佳答案
游戏有点晚了,但您需要基本上将约束布局中的 View 视为具有自己的 LayoutParams 的常规 View 。
在 ConstraintLayout 案例中,文档位于此处:https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout.LayoutParams
This class contains the different attributes specifying how a view want to be laid out inside a ConstraintLayout. For building up constraints at run time, using ConstraintSet is recommended.
因此,推荐的方法是使用 ConstraintSet .
那里有一个很好的代码示例,但核心概念是您需要创建一个新集合(通过复制/克隆/新建等),设置其属性,然后将其应用于您的布局。
例如:假设您的布局包含一个 ConstraintLayout(此处称为 mConstraintLayout)并且其中包含一个 View (示例中为 R.id.go_button),您可以这样做:
ConstraintSet set = new ConstraintSet();
// You may want (optional) to start with the existing constraint,
// so uncomment this.
// set.clone(mConstraintLayout);
// Resize to 100dp
set.constrainHeight(R.id.go_button, (int)(100 * density));
set.constrainWidth(R.id.go_button, (int)(100 * density));
// center horizontally in the container
set.centerHorizontally(R.id.go_button, R.id.rootLayout);
// pin to the bottom of the container
set.connect(R.id.go_button, BOTTOM, R.id.rootLayout, BOTTOM, 8);
// Apply the changes
set.applyTo(mConstraintLayout);
// this is my… (ConstraintLayout) findViewById(R.id.rootLayout);
关于以编程方式进行Android约束布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296627/