天天看點

Android相對布局簡單案例(附完整源碼)

相對布局是采用相對于其他元件的位置的布局方式。在相對布局中,通過指定ID關聯其他元件,進而以右對齊、上對齊、下對齊或螢幕中央對齊等方式來排列元件。

在XML布局檔案中,由根元素RelativeLayout來辨別相對布局。

本博文就以實作圖檔兩種效果為例,講解如何操作:

Android相對布局簡單案例(附完整源碼)

在本文閱覽之前,確定大家會跑第一個hello,world。可以參考這個mooc講的内容

mooc連結

布局步驟

建立新Project

Android相對布局簡單案例(附完整源碼)

點進Project—>Empty Activity—>然後finish即可。成功之後,點選箭頭運作程式。

Android相對布局簡單案例(附完整源碼)

預設配置的話,應該可以跑起來hello world。然後我們繼續做下一個不走

上傳圖檔資源

從網上照一張或者自己搞一張5050~7575之間的圖檔,任意但不要太大,格式任意,名字不要任意。名字英文!規範!初學者就取by吧(測試裡用了by)

Android相對布局簡單案例(附完整源碼)

一定要拖到drawable,比如像這種拖拽,

Android相對布局簡單案例(附完整源碼)

ok後,我們基礎圖檔有了,直接上測試樣例

布局測試源碼

代碼後對此作詳細講解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"

>
    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_centerInParent="true"
        android:src="@drawable/by"
        android:id="@+id/img"
        />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/img"
        android:layout_centerHorizontal="true"
        android:text="上面" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/img"
        android:layout_centerHorizontal="true"
        android:text="下面" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/img"
        android:layout_centerVertical="true"
        android:text="左邊" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/img"
        android:layout_centerVertical="true"
        android:text="右邊" />


</RelativeLayout>
           

RelativeLayout講解

它是來辨別相對布局的,在這裡隻是做了match_parent(比對父元素)

ImageView講解

width與height都是80dp,圖檔路徑是引用@drawable中的by,id是img一定要設,後面要對其操作。centerInparent是對其産生居中操作。

Button講解

width與height包含自身内容,toRightof相對于img的右邊,Left就是左邊,above就是上邊,below就是下邊。centerHorizontal中部水準居中。centerVertical就是中部垂直居中。

修改java類檔案調用

一般按照預設配置,應該是這張圖

Android相對布局簡單案例(附完整源碼)

然後啟動程式,觀察運作效果。

效果如圖

Android相對布局簡單案例(附完整源碼)

最終效果。應該就是這樣。

總結

布局控制所需的步驟不是很多,步驟如下

  • 搭建新類
  • 上傳資源圖檔
  • 編輯布局代碼
  • 更改檔案調用
  • run測試效果

    相對布局就是将原先元件進行覆寫,後期基礎學習都用線性布局,可以參考部落客寫的這個博文:

    Android基礎小白線性布局簡單案例(附完整源碼)

    希望此博文對大家有幫助!