編輯:Android 開發實例
剛接觸 Android 版面時,最常被搞混的就是這幾個屬性:為什麼同樣寫 gravity,放在 LinearLayout 上和放在 Button 上效果完全不同?本文用實際例子把觀念釐清。
只有 LinearLayout 有這個屬性。horizontal 讓子元素由左到右水平排列,vertical 則由上到下垂直排列。
這兩者最大的差異在於「對齊誰」:
· android:gravity:指定本元素的子元素相對自己的對齊方式。
· android:layout_gravity:指定本元素相對父容器的對齊方式。
下面的 LinearLayout 把 gravity 設為 right,兩個子 Button 都會靠右對齊:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="right"
>
<Button android:text="button01" android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button android:text="button02" android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
這次父容器不做設定,改由兩個 Button 各自指定自己在父容器中的位置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_gravity="left"
android:text="button01"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:layout_gravity="right"
android:text="button02"
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
結果是 Button01 靠左、Button02 靠右。要注意的是,在垂直排列的 LinearLayout 中,layout_gravity 主要影響水平方向的位置;水平排列時則影響垂直方向。
FrameLayout 相當於螢幕上預留的一塊空白區域,你可以往裡面填東西。它的特性是:所有子元素都固定在左上角,無法為個別子元素指定位置;後加入的子元素會直接疊在前一個之上,把前面部分或全部遮住(除非後者是透明的)。這個特性讓它很適合做圖片疊字、Loading 遮罩這類效果。
1. 用 xml 定義介面,再由 Activity 的 setContentView() 依定義產生真正的控制項物件。可以把它想成:xml 是設計圖,setContentView 是生產線。
2. FrameLayout 可用的屬性來自三個來源:從父類別繼承而來、由 LayoutParams 嵌套類別定義、以及自身類別定義。查文件時要對應到正確的類別。
3. 幾個最常碰到的屬性:
· android:id:繼承自 android.view.View,為元件提供唯一識別符號,之後可用 findViewById() 取得。
· android:layout_width/android:layout_height:寬與高,定義在 FrameLayout.LayoutParams 中。取值為 fill_parent(現已更名為 match_parent,在指定軸向上撐滿父容器)或 wrap_content(依內容實際大小)。
· android:background:背景
· android:foreground:前景,會疊在所有子元素之上
把三者放在一起記會清楚很多:orientation 決定「怎麼排」,gravity 決定「我的小孩在我體內怎麼靠」,layout_gravity 決定「我在我爸體內怎麼靠」。釐清這三句話,大部分對齊問題都能自己推導出來。
Android 應用本地化:讓同一個 App 說各國語言
一個上架 Google Play 的 App,可能在幾十個國家的裝置上被開啟。使用者對「文字、數字、日期、檔案」的期待各不相同,如果 App 永遠只顯示一種語言,體驗與留
Android ApiDemo 系列七:Activity 堆疊與 Forwarding
Android 應用常包含多個 Activity,使用者在不同畫面之間移動時,系統會以堆疊方式管理這些 Activity。新啟動的 Activity 會疊在目前畫面之上,
用 MediaPlayer 打造快轉、倒退都行的播放器
Android 播放音訊與影片的方式有好幾種,MediaPlayer 是最容易上手的一個。它位於 android.media 套件,除了本機檔案與 res/raw 資源,
Android 多媒體播放:MediaPlayer 控制與進度條同步
MediaPlayer 是 Android 中常用的多媒體播放類別。它可以播放本機音檔、網路串流與影片資源。若要播放放在 res/raw 的音檔,可以使用: Media