学习ConstraintLayout布局

下载了Android Studio 2.2 Preview 5版本,发现新建项目build.gradle文件新增了一个layout插件ConstraintLayout

compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha4'

content_main.xml文件默认采用android.support.constraint.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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.way.once.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="@+id/content_main"
        app:layout_constraintLeft_toLeftOf="@+id/content_main"
        app:layout_constraintRight_toRightOf="@+id/content_main"
        app:layout_constraintTop_toTopOf="@+id/content_main" />

</android.support.constraint.ConstraintLayout>

TextView的4个layout属性:

app:layout_constraintBottom_toBottomOf="@+id/content_main"
app:layout_constraintLeft_toLeftOf="@+id/content_main"
app:layout_constraintRight_toRightOf="@+id/content_main"
app:layout_constraintTop_toTopOf="@+id/content_main"

都是相对于父布局的位置限制,使TextView始终处于居中显示。

然后通过layout_constraintHorizonal_biaslayout_constraintVertical_bias属性可以横向和纵向的位置偏移:

app:layout_constraintVertical_bias="0.8"
 app:layout_constraintHorizontal_bias="0.6"

注意app:layout_constraintVertical_bias=”0.5”相当于没有偏移。

Google Codelabs提供了知识介绍,Demo程序地址为GitHub.

I Don't Want Your Money, I Want Aragaki Yui.