Android约束布局以编程方式进行? [英] Android Constraint Layout Programmatically?
问题描述
在iOS中,我非常喜欢删除情节提要,并使用制图框架将所有内容布置在代码中.这是从制图学的github上偷来的:
In iOS I'm a big fan of deleting the storyboard and using the Cartography framework to lay everything out in code. This is stolen from Cartography's 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是否有与之等效的产品?看来新的约束布局是朝着正确方向迈出的一步,但我想以编程的方式做到这一点.
Is there any equivalent at all for Android? It seems like the new Constraint Layout is a step in the right direction but I would like to do it programmatically.
推荐答案
游戏有点晚了,但是您基本上需要将约束布局中的视图视为仅具有自己的LayoutParams的常规视图.
A little late to the game, but you need to basically treat your views in a constraint layout as regular views that simply have their own LayoutParams.
在ConstraintLayout情况下,文档位于此处: https ://developer.android.com/reference/android/support/constraint/ConstraintLayout.LayoutParams.html
In the ConstraintLayout case, the documentation is located here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.LayoutParams.html
此类包含不同的属性,这些属性指定如何在ConstraintLayout内布局视图.为了在运行时建立约束,建议使用ConstraintSet.
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
So, the recommended method is to use a ConstraintSet.
那里有一个不错的代码示例,但是核心概念是您需要创建一个新集合(通过复制/克隆/新建等),设置其属性,然后将其应用于布局.
There's a nice code sample there, but the core concept is you need to create a new set (by copying/cloning/new, etc), set its properties, and then apply it to your layout.
例如:假设您的布局包含一个ConstraintLayout(此处称为mConstraintLayout),并且其中包含一个视图(示例中为R.id.go_button),则可以执行以下操作:
E.g.: Suppose your layout contains a ConstraintLayout (called mConstraintLayout here) and inside it contains a view (R.id.go_button in the sample), you could do:
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约束布局以编程方式进行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!