ConstraintLayout是一个ViewGroup,可用作支持库,您可以在从API级别9(Gingerbread)开始的Android系统上使用。
RelativeLayout 和 ConstraintLayout 有许多类似的地方。你可以相对地放置你的子视图,这第一眼看起来和 ConstraintLayout 实现的一样。但RelativeLayout 有一些你可能早就知道的问题。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="34dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"/>
</RelativeLayout>
上面的代码在容器的右下方放了一个按钮
如果把RelativeLayout的layout_height改成wrap_content,按钮就直接在容器的底部。
如果使用ConstraintLayout就可以避免这个问题
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_marginBottom="34dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"/>
</android.support.constraint.ConstraintLayout>
具体使用请看下一篇:
约束布局ConstraintLayout的使用(二)