美文网首页
强大的约束布局ConstraintLayout

强大的约束布局ConstraintLayout

作者: 古宇强 | 来源:发表于2019-06-15 19:26 被阅读0次

    1.目录

    2.正文背景

    约束布局顾名思义ConstraintLayout里的子view通过一些约束来确定自己的显示(位置,大小等)。
    子view上下左右的约束属性有以下几个,子view的约束对象可以是其他子view,也可以是ConstraintLayout,因此以下属性的值可以是其他子view的id,也可以是"parent"表示ConstraintLayout

    layout_constraintLeft_toLeftOf ===> 子view左边受哪个view的左边的约束,如此类推
    layout_constraintLeft_toRightOf
    layout_constraintRight_toLeftOf
    layout_constraintRight_toRightOf
    layout_constraintTop_toTopOf
    layout_constraintTop_toBottomOf
    layout_constraintBottom_toTopOf
    layout_constraintBottom_toBottomOf
    layout_constraintStart_toEndOf
    layout_constraintStart_toStartOf
    layout_constraintEnd_toStartOf
    layout_constraintEnd_toEndOf
    layout_constraintBaseline_toBaselineOf

    ConstraintLayout和其他布局下的子view的宽高属性值略有不同。主要体现在充满父布局的属性值不同,其他布局的充满父布局属性为match_parent和约束布局的为match_constraint(即0dp)
    注意:match_constraint的表现受layout_constraintXXX_default值的影响
    ==spread:充满约束空间 默认情况
    ==wrap:匹配内容大小但不超过约束限制
    ==percent:百分比布局

    一图胜千言

    3.百分比布局:屏幕适配

    前提条件:width或height必须为match_constraint(即0dp),否则百分比布局无效
    使用方式:

    android:layout_width="0dp"
    app:layout_constraintWidth_default="percent"
    app:layout_constraintWidth_percent="1"
    
    注意这个百分比是约束布局的百分比

    4.宽高比

    app:layout_constraintDimensionRatio="w,1:2"

    如果要约束w(宽)(即高是定的),w开头,宽高比;h开头,高宽比。

    如果要约束h(高)(即宽是定的),h开头,宽高比;w开头,高宽比。

    如果宽高同时为0dp(宽高都可定的话),那么w开头,表示高定约束宽,宽高比;h开头,表示宽定约束高,宽高比

    5.goneMargin:约束view消失后才起作用的Margin属性


    6.Group统一控制多个控件的显示或隐藏。group的visibility属性比view本身的优先级最高,而且constraint_referenced_ids只能引用约束布局下的直接子view的id。


    7.居中和偏移


    8.链式布局

    packed模式下的偏移
    跟下图对比
    跟上图对比

    9.360度无死角定位布局



    10.Barrier与多个控件集合的某边对齐




    11.GuideLine,当没有合适约束view的时候,可以创建一个guideline作为约束view

    12.PlaceHolder 用placeholder中的约束条件替换对应id的view的约束条件

    应用场景:作为位置模板,引入后只需要写内容view;通过代码动态改变内容,结合TransitionManager可以做一些有趣的过渡动画等


    13.ConstraintSet动态修改约束条件。ConstraintLayout不推荐用LayoutParams来设置属性,而是用ConstraintSet来设置参数。官网中还有个利用ConstraintSet来做场景动画的例子

    14.最后附上官网文档对约束布局的说明链接

    15.写在最后的话,约束布局拖动起来虽然很爽,但布局复杂一些的时候都挤在一起了,靠拖动就不那么愉快了,所以能把需要的属性敲出来才是王道,就那几个属性,记住关键词就行,其他靠智能提示咯。

    相关文章

      网友评论

          本文标题:强大的约束布局ConstraintLayout

          本文链接:https://www.haomeiwen.com/subject/sxakfctx.html