前言
ConstraintLayout即约束布局, 在2016年由Google I/O推出. 从支持力度而言, 将成为主流布局样式, 完全代替其他布局, 减少布局的层级, 优化渲染性能. 且自Android Studio 2.3起创建新的Activity,默认的layout根布局就是ConstraintLayout。
Android Studio 2.3以下的在build.gradle中添加如下依赖:
compile 'com.android.support.constraint:constraint-layout:1.0.2'
距离ConstraintLayout出现至今已经有一年了,所以再不学习就真的晚了。
一、概念
ConstraintLayout约束布局的含义: 根据布局中的其他元素或视图, 确定View在屏幕中的位置, 受到三类约束, 即其他视图, 父容器(parent), 基准线(Guideline).
layout_constraint[当前控件位置]_[目标控件位置]="[目标控件ID]"
例如:
app:layout_constraintTop_toTopOf="@id/tv1"
约束当前View的顶部至目标View的顶部, 目标View是tv1. 简单来说就是把当前View的顶部对齐到tv1的顶部.
二、基本使用
下边看个例子:
这是要给我们经常会写的一个布局样式,我们用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"
android:background="#11ff0000"
tools:context="com.xp.constraintlayout.MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="140dp"
android:layout_height="86dp"
android:layout_marginLeft="12dp"
android:layout_marginTop="12dp"
android:background="@color/colorAccent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="12dp"
android:text="男人看了沉默,女人看了流泪,13亿中国人都惊呆了男人看了沉默"
android:textColor="@android:color/black"
android:textSize="16sp"
app:layout_constraintLeft_toRightOf="@id/tv1"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="@id/tv1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:text="20分钟前"
android:textSize="12sp"
app:layout_constraintLeft_toRightOf="@id/tv1"
app:layout_constraintBottom_toBottomOf="@id/tv1" />
</android.support.constraint.ConstraintLayout>
解释一下几个属性
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
第一个的意思是tv1的左侧与父控件对齐,第二个的意思是顶部对齐父控件。
app:layout_constraintLeft_toRightOf="