android.support.constraint.ConstraintLayout

olivee 4年前 ⋅ 1269 阅读

其它参考: https://www.jianshu.com/p/17ec9bd6ca8a

ConstraintLayout可以按照比例约束控件位置和尺寸,能够更好地适配屏幕大小不同的机型。

例子

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">



    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="确认"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toLeftOf="parent"
        app:layout_constraintLeft_toRightOf="parent"/>

    <EditText
        android:id="@+id/password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintRight_toLeftOf="parent"
        app:layout_constraintLeft_toRightOf="parent"
        android:text=""
     />

    <TextView
        android:id="@+id/warning"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        app:layout_constraintLeft_toLeftOf="@+id/password"
        app:layout_constraintTop_toBottomOf="@+id/password" />

</android.support.constraint.ConstraintLayout>
  • layout_constraint*属性的值可以是某个id或者parent(父布局)

  • B要位于A的右边,则使用app:layout_constraintLeft_toRightOf="@id/a",C位于A的下边,则使用app:layout_constraintTop_toBottomOf="@id/a"

对于一个View的边界界定,官方给了下面这张图:

layout.png