第三篇-以LinearLayout進行Android介面設計
一、新建一個專案
選擇empty activity,此時專案裡面沒有main.java的檔案。
二、手動建立java檔案
Project那兒選擇android模式,在app/java/com....一般是第一個資料夾下,右擊滑鼠new->activity->empty activity。Activity Name、Layout Name隨便取名,但是要取消外觀支援檔的勾即取消Generate Layout File前面的勾。接著在Launcher Activity前打勾,意思是以這個activity作為一個主要的activity,以此為進入點。點選Finish。
三、手動建立外觀檔檔案
app/res,右擊res,new->XML->Layout XML File。Layout File Name 隨便取,不過不能有大寫英文字母,一般有多個英文單詞,中間以_分開。Root Tag選擇類別為LinearLayout。點選Finish。
四、設計layout.xml
按住滑鼠左鍵,拖動三個Button按鈕到手機預覽介面,點選Component Tree下的LinearLayout,在右側Attributes下有一些設定。在LinearLayout標籤下有個orientation選項,預設是horizaontal即水平排列,如果將其改為vertical,會發現Button按鈕變成垂直排列了,且佔滿了豎直的空間,Button大小有點奇怪。在中間介面layout.xml下讓其從Design切換到Text即文字模式,將第一個Button標籤下的android:layout_weight="1"去掉,會發現最上面的按鈕大小縮小了。將剩下兩個Button下的這句話也去掉,會發現樣子正常了。在將介面切換到Design模式,將orientation改回horizontal模式,三個按鈕變成橫排了,不過不再佔據一整行,可以在拖動一個按鈕進去。並在文字模式下將其weight刪掉。回到Design介面,點選螢幕上最左側的Button,在右側text處為它取名為Button #1,並依次將後面三個按鈕改名為Button #2,Button #3,Button #4,由於Button #4沒有足夠的位置,它的文字變成兩行了。點選Button #1將其layout_width改為match_parent,那麼Button #1就會佔據一行,2,3,4個按鈕都會不見。如果點選LinearLayout將orientation換成vertical,2,3,4個出現在下面垂直排列。依次點選Button2,3,4,將layout_width 都選擇match_parent,則四個按鈕會垂直排列,寬度就是一整行。
效果圖如下:
layout.xml中text程式碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button #1" /> <!--android:layout_weight="1"--> android:text="Button" /> <Button android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button #2" /> <!--android:layout_weight="1"--> android:text="Button" /> <Button android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button #3" /> <!--android:layout_weight="1"--> android:text="Button" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button #4" /> <!--android:layout_weight="1"--> android:text="Button" /> </LinearLayout>
最後開啟之前建立的main.java,在super.onCreate(saveInstanceState);後面加上setContentView(R.layout.layout);整個簡單的程式就完成了,就以編譯執行。