為什么ConstraintLayout代替其他布局?

歡迎Follow我的GitHub, 關(guān)注我的簡書. 其余參考Android目錄.

Constraint Layout

本文的合集已經(jīng)編著成書,高級Android開發(fā)強(qiáng)化實戰(zhàn)颜骤,歡迎各位讀友的建議和指導(dǎo)毅待。在京東即可購買:https://item.jd.com/12385680.html

Android

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

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

本文源碼的GitHub下載地址

概念

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

layout_constraint[本源位置]_[目標(biāo)位置]="[目標(biāo)ID]"

例如:

app:layout_constraintBottom_toBottomOf="@+id/constraintLayout"

約束當(dāng)前View的底部目標(biāo)View的底部, 目標(biāo)View是constraintLayout. 即, 把當(dāng)前View的底部對齊到constraintLayout的底部.

演示

本例復(fù)用的Activity頁面, 根據(jù)不同的參數(shù)設(shè)置對應(yīng)的標(biāo)題和布局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); // 設(shè)置頁面布局, 復(fù)用布局
    }
}

主頁面使用ListView展示多項, 每項對應(yīng)不同的布局頁面.

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) {
                // 復(fù)用顯示布局
                Intent intent = new Intent(MainActivity.this, LayoutDisplayActivity.class);
                intent.putExtra(Intent.EXTRA_TITLE, LIST_ITEMS[i]); // 標(biāo)題
                intent.putExtra(LayoutDisplayActivity.EXTRA_LAYOUT_ID, LAYOUT_IDS[i]); // 布局Id
                startActivity(intent);
            }
        });
    }
}

基礎(chǔ)

ConstraintLayout最基本的使用方式, 就是指定約束. 如, 取消按鈕的底部對齊constraintLayout(父容器)的底部, 左側(cè)對齊父容器的左側(cè). 下一步按鈕的底部對齊父容器的底部, 而左側(cè)對齊取消按鈕的右側(cè), 每個按鈕添加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的屬性設(shè)置, 最重要的就是理解屬性的表示含義.

Base

比例

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

constraintHorizontal_bias設(shè)置水平比例, constraintVertical_bias設(shè)置豎直比例.

<?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>
Bias

引導(dǎo)線

ConstraintLayout除了與視圖約束以外, 還支持與引導(dǎo)線(Guideline)約束. 如, 設(shè)置豎直引導(dǎo)線(Guideline)距離左側(cè)72dp. 兩個按鈕的左側(cè)都與引導(dǎo)線約束, 上下使用比例方式排列, 一個是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>
Guide Line

視圖尺寸

ConstraintLayout也支持自動填充寬高, 把寬高設(shè)置為0dp會根據(jù)位置自動填充. 如, Large按鈕, 左側(cè)與Small按鈕的左側(cè)對齊, 右側(cè)與constraintLayout(父控件)的右側(cè)對齊, 寬度設(shè)置為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>
Measure

縱橫比

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

<?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>
Ratio

鏈樣式

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

Chain

app:layout_constraintHorizontal_chainStyle設(shè)置水平鏈.

<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" />

通過不同的鏈?zhǔn)浇M合, 生成復(fù)雜的視圖樣式.

Chains

ConstraintLayout的基本使用方式就是這些, 兼顧LinearLayout與RelativeLayout的優(yōu)點(diǎn), 非常適合構(gòu)建復(fù)雜布局, 降低布局的層級, 加快渲染速度.

OK, that's all! Enjoy it!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市喧伞,隨后出現(xiàn)的幾起案子狞山,更是在濱河造成了極大的恐慌全闷,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件萍启,死亡現(xiàn)場離奇詭異总珠,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)勘纯,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進(jìn)店門局服,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人驳遵,你說我怎么就攤上這事淫奔。” “怎么了堤结?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵搏讶,是天一觀的道長佳鳖。 經(jīng)常有香客問我,道長媒惕,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任来庭,我火速辦了婚禮妒蔚,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘月弛。我一直安慰自己肴盏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布帽衙。 她就那樣靜靜地躺著菜皂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪厉萝。 梳的紋絲不亂的頭發(fā)上恍飘,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天,我揣著相機(jī)與錄音谴垫,去河邊找鬼章母。 笑死,一個胖子當(dāng)著我的面吹牛翩剪,可吹牛的內(nèi)容都是我干的乳怎。 我是一名探鬼主播,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼前弯,長吁一口氣:“原來是場噩夢啊……” “哼蚪缀!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起恕出,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤询枚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后剃根,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體哩盲,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年狈醉,在試婚紗的時候發(fā)現(xiàn)自己被綠了廉油。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片开仰。...
    茶點(diǎn)故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡乃沙,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出夕冲,到底是詐尸還是另有隱情渣慕,我是刑警寧澤嘶炭,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布抱慌,位于F島的核電站,受9級特大地震影響眨猎,放射性物質(zhì)發(fā)生泄漏抑进。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一睡陪、第九天 我趴在偏房一處隱蔽的房頂上張望寺渗。 院中可真熱鬧,春花似錦兰迫、人聲如沸信殊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽涡拘。三九已至,卻和暖如春据德,著一層夾襖步出監(jiān)牢的瞬間鳄乏,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工晋控, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留汞窗,地道東北人。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓赡译,卻偏偏與公主長得像仲吏,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子蝌焚,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容