如果要将现有布局转换为约束布局,只需按照下列步骤操作:
- 在 Android Studio 中打开布局,然后单击编辑器窗口底部的 Design 选项卡。
- 在 Component Tree 窗口中,右键单击布局,然后单击 Convert layout to ConstraintLayout。
开始
要在项目中使用 ConstraintLayout
,我们需要在 build.gradle
中添加依赖(新版 AndroidStudio 会默认添加):
compile ‘com.android.support.constraint:constraint-layout:1.0.2’
然后,在工具栏中同步 Gradle
文件。
创建布局
接下来,我们创建一个布局,根布局就用 ConstraintLayout
:
<android.support.constraint.ConstraintLayout
xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
</android.support.constraint.ConstraintLayout>
添加约束
添加约束十分简单,我们首先从 Design
界面的 Palette
操作栏拖动一个 Button
到蓝图中,添加完后,点击选中它,效果是这样的:
可以看到,上下左右都有一个小圆圈,这个圆圈就是用来添加约束的。 四个角的矩形,是用来扩大或缩小控件的。
:删除选中控件的所有约束。
:编辑基线,用于基线对齐(下面会说)。
现在我们来为这个 Button
添加约束:
看这个效果,有没有一种「五马分尸」的感觉?当只有一条边拉这个 Button
时,Button
马上就被拉过去了,但是当四个边都开始拉这个 Button
时,Button
就在中间动弹不得了。