当前位置: 移动技术网 > IT编程>移动开发>Android > AndroidStudio2.2新功能ConstraintLayout的使用介绍

AndroidStudio2.2新功能ConstraintLayout的使用介绍

2018年09月29日  | 移动技术网IT编程  | 我要评论

物流在职研究生,畏首畏尾,云浮haobc.vip

constraintlayout是androidstudio2.2新增的一个功能,那么这个到底是什么呢?首先第一点我们知道传统的安卓开发,页面基本都是xml编写实现,特别在一些复杂的页面上需要嵌套多层,降低了页面加载的效率,因为constraintlayout就可以很好的优化布局,还有一点我们羡慕ios的拖拽xml页面在这里也可以更好的实现。当然我所说的以上两点都是优化以前的布局,这也是google极力要做的事情

开始

想要使用constraintlayout,首先as版本必须升级到2.2以上(我基本都是逢新必更),首先需要在app/build.gradle文件中添加constraintlayout依赖

implementation 'com.android.support.constraint:constraint-layout:1.1.2'

然后在项目的build.gradle文件buildscript和allprojects的repositories中添加google()

allprojects {
  repositories {
    google()
    jcenter()
   }
}

然后同步就可以愉快的使用constraintlayout了~~

1. layout_constraint[自身控件位置]_to[目标控件位置]of=="[目标控件id]"

layout_constraintleft_toleftof

layout_constraintleft_torightof

layout_constraintright_toleftof

layout_constraintright_torightof

layout_constrainttop_totopof

layout_constrainttop_tobottomof

layout_constraintbottom_totopof

layout_constraintbottom_tobottomof

layout_constraintbaseline_tobaselineof

layout_constraintstart_toendof

layout_constraintstart_tostartof

layout_constraintend_tostartof

layout_constraintend_toendof

看到这些猜也能猜出个大概~比如layout_constraintleft_toleftof就是说当前控件的left在目标控件的left上。如果目标控件为父控件则id可以直接写成parent。比如要实现b控件在a控件右面,则在b控件中设置layout_constraintleft_torightof。意思就是说b控件的左面在a控件的右面~

\

2. margins

android:layout_marginstart

android:layout_marginend

android:layout_marginleft

android:layout_margintop

android:layout_marginright

android:layout_marginbottom

这个与之前其他viewgroup属性一致,不一样的就是多了以下几点:

layout_gonemarginstart

layout_gonemarginend

layout_gonemarginleft

layout_gonemargintop

layout_gonemarginright

layout_gonemarginbottom

gonemargin属性是指目标控件gone掉之后,自身控件可以设置个margin值,这里有一点需要敲黑板,目标控件就是相对于的那个控件

3. bias

`layout_constrainthorizontal_bias``

layout_constraintvertical_bias

这个属性的意思是可以使用偏差属性调整定位以使一侧偏向另一侧,即控件距离左右百分比(layout_constrainthorizontal_bias)和距离上下百分比(layout_constraintvertical_bias)

\

4. wrap_content : enforcing constraints (*added in 1.1*)

强制约束

app:layout_constrainedwidth=”true|false”

app:layout_constrainedheight=”true|false”

true代表防止约束失效,默认为false,比如:b在a的右边app:layout_constraintleft_torightof="@+id/a",但是当a的内容越来越多并且超过了a到父控件最右的距离,此时就会约束失效使b的一部分出现了a的非右边。如果b设置了该属性为true,则b始终出现在a的右边,不会发生约束失效

5. ratio


app:layout_constraintdimensionratio="h,16:9"

不用多说百分比布局是android中常用的一种适配布局h或w则代表以高或宽为基准

6. guideline

layout_constraintguide_begin 距离父容器起始位置的距离(左侧或顶部)

layout_constraintguide_end 距离父容器结束位置的距离(右侧或底部)

layout_constraintguide_percent 距离父容器宽度或高度的百分比

其实很好理解,比如


 

  

则表示在垂直方向上画一根基准线(只是参考线,并不进行view绘制)然后其他控件可以根据这条线进行放置

\

7. barrier




  

  

  

\

显而易见,你可以把他看做一个容器constraint_referenced_ids=控件id,然后把这些控件看做一个整体

8. group

它和barrier有异曲同工之处,相同的都是你可以把他们看做一个容器,不同的是他是控制整个容器之中的所有的控件的可见或者不可见,比如android:visibility="gone",那它所包裹的左右控件都会gone。

当然constraintlayout的api不止这些,需要我们真真切切的去使用它,你会发现它真的很好用~

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网