1. 程式人生 > >第四篇-以ConstraintLayout進行Android介面設計

第四篇-以ConstraintLayout進行Android介面設計

此文章基於第三篇。

一、新建一個layout.xml檔案,建立方法不再贅述,在Design介面右擊LinearLayout,點選Convert LinearLayout to ConstraintLayout,選擇ok。

二、將main.java中setContentView(R.layout.layout);刪掉,換成setContentView(R.layout.layout2);即用新建的cpntrainlayout xml檔案。

三、切換到layout2.xml,拖動Button到手機預覽介面的右下角,會發現上面有個紅色的感嘆號,點選可以看到說沒有設定位置。將滑鼠放在Button上,可以看見上下左右有四個小圓圈,可以通過這四個小圓圈用滑鼠將其連在對應的牆壁,控制Button的位置,如果想將其放在右下角,那麼就將右邊的小圓圈按住滑鼠左鍵拉到右邊的牆壁,Button右側就和牆壁貼在一起,同理,將下面的小圓圈和介面底部連線,Buttonjiu 固定在右下角了。如果想取消之前的連線,將滑鼠放在已經連線的小圓圈上,會發現小圓圈填充了紅色,並顯示Delete Connection,點一下就可以取消連線了。如果全都不設定連線,預設是從上到下,從左到右。將四個圓圈全部連線,Button就會出現在正中間。選擇layout_width為match_constraint,button就會佔一整行。寫入text為Button #1。取消下方的連線,Button#1就會跑到最上面。

拖動另一個Button到預覽介面,連線左右兩面,將text變為Button #2。並將Button #2上方的小圓圈連線Button #1下方的小圓圈,並改變layout_width為match_constraint,那麼Button #2就會出現在Button #1的下方了。拖動第三個Button按鈕,連線左右下方向,將text變為Button #3,改變layout_width為match_constraint,此時Button #3出現在底部。

效果圖:

layout2.xml程式碼如下:

<?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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="Button #1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="Button #2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button5" />

    <Button
        android:id="@+id/button7"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>

  至此,ConstraintLayout部分完成了。可以執行。