美文网首页
ConstraintLayout优化布局

ConstraintLayout优化布局

作者: Neo_duan | 来源:发表于2019-05-10 16:27 被阅读0次

ConstraintLayou布局优点

减少View树的嵌套,从而减少了onMeasure和onLayout,使性能更加高效
约束的方式来指定各个控件的位置和关系的,它有点类似于RelativeLayout,但远比RelativeLayout要更强大。

compile 'com.android.support.constraint:constraint-layout:1.0.2' //可能有最新版

属性解读

app:layout_constraintRight_toRightOf="parent"自己的左与父控件左对齐,相当于在parent中居左
app:layout_constraintLeft_toLeftOf="parent" 自己的右与父控件右对齐,相当于在parent中居右
以上两个属性都加上,说明左右都拉伸,居parent中:水平居中

同理:上下拉伸则垂直居中
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"


app:layout_constraintLeft_toLeftOf="@id/viewB" 自己的左与控件viewB左对齐
layout_constraintLeft、top、right、bottom代表约束自己的左上右下

同理:
layout_constraintRight_toLeftOf
layout_constraintRight_toRightOf
layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
layout_constraintBaseline_toBaselineOf

偏斜bias属性:

默认值是0.5
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.2"

以上为:左右拉伸居中后,水平偏斜20%,相当于控件离parent 20%

同理:上下居中,再偏斜20%
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintVertical_bias="0.2"

比例/率(Ratio)

控制控件宽高大小的比例,该控件宽高至少有一个为0
<Button
    android:layout_width="200dp"
    android:layout_height="0dp"
    android:layout_marginStart="10dp"
    android:text="居中"
    app:layout_constraintDimensionRatio="2:1"/>
    
android:layout_height="0dp"其实代表match_parent
app:layout_constraintDimensionRatio="2:1"表示宽高比为2:1

chain

app:layout_constraintHorizontal_weight="1" 水平比重,宽度width还是要设置为0dp

GuideLine辅助线

//定义一个基准线,这个是不会在UI上显示的
android:orientation="vertical"代表竖直的基准线
app:layout_constraintGuide_percent="0.5"基准线居中,如果是0.2代表基准线距离parent 20%
    
<android.support.constraint.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintGuide_percent="0.5"
    android:orientation="vertical"/>
    
    
//登录按钮在基准线的左边
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintRight_toLeftOf="@id/guideline"
    android:text="登录"/>

//注册按钮在基准线右边
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toRightOf="@id/guideline"
    android:text="注册"/>
    
总结:ConstraintLayou约束布局其实就是结合了RelativeLayout和LinearLayout的属性

相关文章

网友评论

      本文标题:ConstraintLayout优化布局

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