編輯:關於 Android 程式設計
Android 應用的圖形介面由 View 與 ViewGroup 物件組成的階層結構建構而成。View 通常是按鈕、文字欄等 UI 元件,而 ViewGroup 則是定義子元件排列方式的不可見容器,例如網格或縱向清單。Android 提供對應的 XML 詞彙,讓你能用 XML 定義介面的元素階層。
用 XML 而非執行期程式碼宣告版面有個重要好處:能為不同螢幕尺寸建立各自的版面配置。
開啟 res/layout/ 下的 activity_main.xml,先刪除 <TextView> 元素,並將 <RelativeLayout> 改為 <LinearLayout>,再加入 android:orientation 並設為 "horizontal":
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
LinearLayout 會依 android:orientation 屬性以垂直或水平方式排列子元件,每個子元件依 XML 中的順序呈現。作為根視圖,它將寬高設為 "match_parent" 以填滿整個可用區域。
在 <LinearLayout> 中加入 <EditText> 以建立可編輯的文字欄:
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
關於這些屬性:android:id 提供元件的唯一識別碼,讓你能在程式碼中參照它;@ 符號在 XML 中參照任何資源時都必須使用,而 + 符號僅在第一次定義資源 ID 時需要。android:layout_width 與 height 使用 "wrap_content" 表示僅佔據容納內容所需的大小。android:hint 則是文字欄為空時顯示的預設字串。
介面中的文字應一律以資源形式指定,便於集中管理與多語言本地化。開啟 res/values/strings.xml,刪除名為 "hello_world" 的元素,新增 "edit_message" 並設值為 "Enter a message",同時為按鈕加入 "button_send":
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>
緊接著 <EditText> 加入 <Button>:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
目前 EditText 與 Button 都只佔內容所需大小。對按鈕來說沒問題,但文字欄可能輸入較長內容,因此最好用 weight 屬性讓它填滿剩餘寬度。weight 是相對權重值,例如一個 view 權重為 2、另一個為 1,總和為 3,則前者佔 2/3、後者佔 1/3。所有 view 的預設 weight 為 0,因此只要給 EditText 一個大於 0 的值,它就會填滿其餘空間:
<EditText
android:layout_weight="1"
android:layout_width="0dp"
... />
使用 weight 時,建議把 EditText 的寬度設為 0dp 以提升效能,因為 "wrap_content" 會需要先計算一個最終無用的寬度,反而多餘。
完整的版面配置檔如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="@+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />
</LinearLayout>
在 Eclipse 中點選 Run,或於命令列執行 ant debug 再透過 adb install 安裝,即可看到成果。
Android 自訂義圓形進度條:打造清晰的任務完成視覺
在 Android 介面設計中,圓形進度條常用於呈現任務完成比例、課程進度或資料載入狀態。相比傳統橫向進度條,圓形設計更容易聚焦視線,也更能營造現代感。實作這類效果時,可
Android 特色開發:傳感器的使用
1、傳感器簡介 手機中內置的傳感器是一種微型的物理設備,它能探測、感受外界的訊號,並按一定規律轉換成我們所需要的資訊。Android 手機通常支持多種類型的傳感器,如光照
android.graphics.Camera:用幾行程式做出簡單的 3D 翻轉效果
Android 的 android.graphics.Camera 並不是拍照用的那個 Camera,而是一個以「相機視點」概念操作 Matrix 的工具類別。透過它
MVC 設計模式在 Android 專案中的落地實踐
學 Android 到第三年,才慢慢意識到一件事:真正拉開專案品質差距的,往往不是 API 用得熟不熟,而是有沒有好的架構與設計模式。基礎知識固然是地基,但當專案規模上來