android ConstraintLayout使用记录

背景

在2016年的Google I/O大会上 , Google 发布了Android Studio 2.2预览版,同时也发布了Android 新的布局方案 ConstraintLayout , 但是最近的一年也没有大规模的使用。2017年Google发布了 Android Studio 2.3 正式版,在 Android Studio 2.3 版本中新建的Module中默认的布局就是 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.constraintlayout.app.MainActivity">
</android.support.constraint.ConstraintLayout>

在使用 ConstraintLayout 的布局方案,需要在 build.gradle 引入支持库:

dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
}

ConstraintLayout向下兼容 API 9常用方法总结

layout_constraintTop_toTopOf       // 将所需视图的顶部与另一个视图的顶部对齐。 

layout_constraintTop_toBottomOf    // 将所需视图的顶部与另一个视图的底部对齐。 

layout_constraintBottom_toTopOf    // 将所需视图的底部与另一个视图的顶部对齐。 

layout_constraintBottom_toBottomOf // 将所需视图的底部与另一个视图的底部对齐。 

layout_constraintLeft_toTopOf      // 将所需视图的左侧与另一个视图的顶部对齐。 

layout_constraintLeft_toBottomOf   // 将所需视图的左侧与另一个视图的底部对齐。 

layout_constraintLeft_toLeftOf     // 将所需视图的左边与另一个视图的左边对齐。 

layout_constraintLeft_toRightOf    // 将所需视图的左边与另一个视图的右边对齐。 

layout_constraintRight_toTopOf     // 将所需视图的右对齐到另一个视图的顶部。

layout_constraintRight_toBottomOf  // 将所需视图的右对齐到另一个的底部。

layout_constraintRight_toLeftOf    // 将所需视图的右边与另一个视图的左边对齐。

layout_constraintRight_toRightOf   // 将所需视图的右边与另一个视图的右边对齐。

遇到的问题:

1. android.support.constraint.ConstraintLayout 1.1.x 以上才有百分比属性,否则报错  

app:layout_constraintWidth_percent="0.5"
app:layout_constraintHeight_percent="0.5"
 

2. ConstraintLayout 要使用app:layout_constraintVertical_bias="0.1" 设置的属性生效,前置条件是设置了top和bottom的约束,app:layout_constraintHorizontal_bias,要设置左右的约束,左右的约束只要设置一个就可以使用了。


app:layout_constraintTop_toBottomOf="parent"
app:layout_constraintBottom_toTopOf="parent"
 

3.动态设置ConstraintLayout 中子view的宽高,通过ConstrainSet.

如:

ConstraintSet constraintSet = new ConstraintSet();

constraintSet.constrainWidth(子view的id,width);

constraintSet.constrainHeight(子view的id,height);

constraintSet.applyTo(goodcoursePlayLayout);//goodcoursePlayLayout是ConstraintLayout

4.constraintlayout 中RecyclerView 显示不完全,需要添加约束条件

 app:layout_constraintBottom_toBottomOf="parent"

暂时这么多,持续补充中...

猜你喜欢

转载自blog.csdn.net/fepengwang/article/details/102584303