Android约束布局ConstraintLayout 项目实战攻略

本文详细介绍了Android约束布局ConstraintLayout的使用,包括概念、基本使用、宽高比、横竖比例、链样式和引导线的实践应用。通过实例解析,帮助开发者掌握如何创建高效、复杂的布局,并提供源码供下载参考。
摘要由CSDN通过智能技术生成

前言

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="
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值