ConstraintLayout的基本用法

  1. 作用
    ConstraintLayout是用来帮助我们用可视化的界面编写XML文件的。
    通常的XML文件不适合用可视化化的界面编写,ConstraintLayout使得这一情况有了很大的改观:


    效果图

    ConstraintLayout可以通过可视化的操作,生成XML代码。并且因为使用约束来定义不同控件的位置和他们的关系,因此,性能上也很不错。

  2. 使用
    Android Studio 生成的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="com.mingpin.android.amazingmemory.AmazingMemoryActivity">

</android.support.constraint.ConstraintLayout>

buile.gradle module:app里的依赖:

dependencies {
   implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

添加控件的约束,来满足需要显示的位置信息(预览里出现的位置,不一定是运行时出现的位置)

  • 单一控件添加约束时,可以点击控件,拖动控件的4个圆圈,会出现箭头,将其引导至边界。


    单一控件添加约束

    根据需要,对4个边界添加约束。

  • 不同控件之间的约束
    比如我们添加一个TextView控件,让其位于LinearLayout的上方64dp,那么我们选择TextView控件,在它的下方的圈处点击,使其箭头指向ConstraintLayout的上方圆圈,调整TextView 的位置,使其距离ConstraintLayout 64dp。


    多控件约束

XML代码添加:

<TextView
        android:id="@+id/textView"
        android:layout_width="249dp"
        android:layout_height="40dp"
        android:layout_marginBottom="64dp"
        android:gravity="center_vertical|center_horizontal"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout" 
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="@string/select_oneway" />

如果有其他控件,以此方式建立约束。

  • 约束删除


    删除约束

    将鼠标停在圆圈上,出现提示时,点击左键就可以删除了。或者选中整个控件,点击
    <-X按钮,可以删除真个控件的约束(图左下的<-X按钮)。

Attribute的几种属性

  • Fixed


    Fixed

    Fixed实际效果:


    Fixed效果
  • MatchConstraints


    MatchConstraints

    MatchConstraints效果:不同于MatchParent,MatchConstraints受控件约束影响。


    MatchConstraints效果
  • WrapContent


    WrapContent

    WrapContent效果:


    WrapContent效果

基本的ConstraintLayout用法到此就结束了,我们应该已经可以通过此方法处理一些简单的页面布局应用了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容