爲什麼ConstraintLayout代替其他佈局?

歡迎Follow我的GitHub, 關注我的簡書. 其餘參考Android目錄.

749674-b3b7e0677d29e778.png
Constraint Layout

本文的合集已經編著成書,高級Android開發強化實戰,歡迎各位讀友的建議和指導。在京東即可購買:https://item.jd.com/12385680.html

749674-8bdd0e74ad4cd66d.png
Android

ConstraintLayout, 即約束佈局, 在2016年由Google I/O推出. 從支持力度而言, 將成爲主流佈局樣式, 完全代替其他佈局, 減少佈局的層級, 優化渲染性能. 在新版Android Studio中, ConstraintLayout已替代RelativeLayout, 成爲HelloWorld項目的默認佈局. ConstraintLayout作爲非綁定(Unbundled)的支持庫, 命名空間是app:, 即來源於本地的包命名空間. 最新版本是1.0.1(2017.4.21), 在項目的build.gradle中聲明.

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

本文源碼的GitHub下載地址

概念

ConstraintLayout約束佈局的含義: 根據佈局中的其他元素或視圖, 確定View在屏幕中的位置, 受到三類約束, 即其他視圖, 父容器(parent), 基準線(Guideline).

layout_constraint[本源位置]_[目標位置]="[目標ID]"

例如:

app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"

約束當前View的底部目標View的底部, 目標View是constraintLayout. 即, 把當前View的底部對齊到constraintLayout的底部.

演示

本例複用的Activity頁面, 根據不同的參數設置對應的標題和佈局ID.

public class LayoutDisplayActivity extends AppCompatActivity {
    private static final String TAG = LayoutDisplayActivity.class.getSimpleName();
    static final String EXTRA_LAYOUT_ID = TAG + ".layoutId"; // 佈局ID

    @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE));
        final int layoutId = getIntent().getIntExtra(EXTRA_LAYOUT_ID, 0);
        setContentView(layoutId); // 設置頁面佈局, 複用佈局
    }
}

主頁面使用ListView展示多項, 每項對應不同的佈局頁面.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView list = (ListView) findViewById(R.id.activity_main);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, LIST_ITEMS);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 複用顯示佈局
                Intent intent = new Intent(MainActivity.this, LayoutDisplayActivity.class);
                intent.putExtra(Intent.EXTRA_TITLE, LIST_ITEMS[i]); // 標題
                intent.putExtra(LayoutDisplayActivity.EXTRA_LAYOUT_ID, LAYOUT_IDS[i]); // 佈局Id
                startActivity(intent);
            }
        });
    }
}

基礎

ConstraintLayout最基本的使用方式, 就是指定約束. 如, 取消按鈕的底部對齊constraintLayout(父容器)的底部, 左側對齊父容器的左側. 下一步按鈕的底部對齊父容器的底部, 而左側對齊取消按鈕的右側, 每個按鈕添加Margin空隙.

父容器可以直接指定ID, 也可以使用parent代指.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:id="@+id/constraintLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        android:text="取消"
        app:layout_constraintBottom_toBottomOf="@id/constraintLayout"
        app:layout_constraintStart_toStartOf="@id/constraintLayout"/>

    <Button
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginStart="16dp"
        android:text="下一步"
        app:layout_constraintBottom_toBottomOf="@id/constraintLayout"
        app:layout_constraintStart_toEndOf="@id/cancel_button"/>

</android.support.constraint.ConstraintLayout>

ConstraintLayout的屬性設置, 最重要的就是理解屬性的表示含義.

749674-b353f4776b665574.png
Base

比例

ConstraintLayout除了指定約束, 還支持設置比例. Center按鈕的全部邊界與constraintLayout(父容器)邊界對齊, 則爲居中. 同時還可以設置水平與豎直的比例, 如Bias按鈕, 在對齊父容器後, 設置水平與豎直的比例均爲0.25, 表示左側與右側比例是1:4, 上部與下部的比例是1:4.

constraintHorizontal_bias設置水平比例, constraintVertical_bias設置豎直比例.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Center"
        app:layout_constraintEnd_toEndOf="@id/constraintLayout"
        app:layout_constraintStart_toStartOf="@id/constraintLayout"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bias"
        app:layout_constraintEnd_toEndOf="@id/constraintLayout"
        app:layout_constraintStart_toStartOf="@id/constraintLayout"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
        app:layout_constraintHorizontal_bias="0.25"
        app:layout_constraintVertical_bias="0.25"/>

</android.support.constraint.ConstraintLayout>
749674-f38d9df8a498ab43.png
Bias

引導線

ConstraintLayout除了與視圖約束以外, 還支持與引導線(Guideline)約束. 如, 設置豎直引導線(Guideline)距離左側72dp. 兩個按鈕的左側都與引導線約束, 上下使用比例方式排列, 一個是0.25, 一個是0.75.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.Guideline
        android:id="@+id/guideLine"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_begin="72dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Guide Up"
        app:layout_constraintStart_toStartOf="@id/guideLine"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
        app:layout_constraintVertical_bias="0.25"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Guide Down"
        app:layout_constraintStart_toStartOf="@id/guideLine"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
        app:layout_constraintVertical_bias="0.75"/>

</android.support.constraint.ConstraintLayout>
749674-00ba9473f6b343ec.png
Guide Line

視圖尺寸

ConstraintLayout也支持自動填充寬高, 把寬高設置爲0dp會根據位置自動填充. 如, Large按鈕, 左側與Small按鈕的左側對齊, 右側與constraintLayout(父控件)的右側對齊, 寬度設置爲0dp, 則會填充全部空位.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:id="@+id/constraintLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Small"
        app:layout_constraintStart_toStartOf="@id/constraintLayout"
        app:layout_constraintTop_toTopOf="@id/constraintLayout"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Large"
        app:layout_constraintBottom_toBottomOf="@id/constraintLayout"
        app:layout_constraintEnd_toEndOf="@id/constraintLayout"
        app:layout_constraintStart_toEndOf="@id/small"
        app:layout_constraintTop_toTopOf="@id/constraintLayout"/>

</android.support.constraint.ConstraintLayout>
749674-90a869a87981e054.png
Measure

縱橫比

ConstraintLayout支持使用constraintDimensionRatio設置寬高的縱橫比, 把寬(layout_width)或者高(layout_height)設置爲0dp, 則根據另一個屬性值和比例, 計算當前屬性值.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    android:id="@+id/constraintLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@color/colorAccent"
        android:src="@drawable/total_large"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
        app:layout_constraintLeft_toLeftOf="@+id/constraintLayout"
        app:layout_constraintRight_toRightOf="@+id/constraintLayout"
        app:layout_constraintTop_toTopOf="@+id/constraintLayout"
        app:layout_constraintDimensionRatio="16:9"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:background="@color/colorAccent"
        android:contentDescription="@null"
        android:src="@drawable/total_large"
        app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"
        app:layout_constraintDimensionRatio="4:3"
        app:layout_constraintLeft_toLeftOf="@+id/constraintLayout"
        app:layout_constraintRight_toRightOf="@+id/constraintLayout"/>

</android.support.constraint.ConstraintLayout>
749674-59210569c57c70de.png
Ratio

鏈樣式

ConstraintLayout同時支持鏈樣式, 這與LinearLayoutlayout_weight屬性非常類似, 通過設置不同的樣式排列元素.

749674-82bec83624cf5787.png
Chain

app:layout_constraintHorizontal_chainStyle設置水平鏈.

<TextView
    android:id="@+id/property_tv_cst_aries"
    style="@style/MemberWidget.Constellation"
    android:layout_marginLeft="@dimen/spacing_big"
    android:layout_marginTop="@dimen/spacing_medium"
    android:onClick="@{listener::onConstellationSelected}"
    android:text="白"
    app:layout_constraintHorizontal_chainStyle="spread_inside"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/property_tv_cst_taurus"
    app:layout_constraintTop_toBottomOf="@id/property_tv_constellation" />

通過不同的鏈式組合, 生成複雜的視圖樣式.

749674-a41568c622dd1c52.png
Chains

ConstraintLayout的基本使用方式就是這些, 兼顧LinearLayout與RelativeLayout的優點, 非常適合構建複雜佈局, 降低佈局的層級, 加快渲染速度.

OK, that's all! Enjoy it!

發佈了35 篇原創文章 · 獲贊 2 · 訪問量 4383
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章