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"

 

暫時這麼多,持續補充中...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章