Android中4種基本佈局簡單介紹和總結
阿新 • • 發佈:2019-02-13
Android中4種基本佈局
線性佈局LinearLayout
LinearLayout線性佈局,是一種非常常用的佈局方式。此佈局會將控制元件線上性方向上依次排列,方向有水平和垂直兩種,首先看一下垂直方向上的佈局格式,程式碼如下:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id ="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一個按鈕"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text ="第二個按鈕"/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第三個按鈕"/>
</LinearLayout>
我們在LinearLayout中添加了三個Button,每個Button的長和寬都是wrap_content,並在android:orientation中指定了排列方向是vertical即垂直方向,執行結果如下圖:
然後我們修改一下LinearLayout的排列方向:
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
....
</LinearLayout>
將android:orientation中屬性值從vertical改為horizontal,即將排列方向從垂直改為水平方向,執行結果如下:
這裡要注意一點 如果LinearLayout的排列方向是horizontal,內部的控制元件就絕對不能將寬度指定為match_parent,因為這樣,一個控制元件就會將水平方向佔滿,其他的控制元件就沒法放了,vertical亦如此。
相對佈局RelativeLayout
這是一個常用的佈局,可以通過相對定位的方式讓控制元件出現在佈局的任何位置
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一個按鈕"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btn1"
android:text="第二個按鈕"/>
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/btn2"
android:text="第三個按鈕"/>
</RelativeLayout>
執行結果:
幀佈局FrameLayout
這個比較簡單,沒有方便的定位方式,所有的控制元件都預設擺放在佈局的左上角。不是很常用。
百分比佈局
這是以前沒有的新增佈局,為了解決控制元件平分佈局的難題,在這種佈局中,不再使用wrap_content和match_parent來指定控制元件大小,而是直接指定控制元件在佈局中所佔百分比,這樣就可以輕鬆實現平分佈局甚至任意比例分割佈局