編輯:Android 開發實例
本篇文章將帶大家實作一個典型的手機表單輸入介面。畫面(也就是 Activity 的窗體)在視覺上可切分為三個區塊:
用到的核心元件包括:RelativeLayout(相對佈局)、ScrollView(捲動視圖)以及 TableLayout(表格佈局)。
要實現「頂部固定、底部固定、中間自動填滿」的效果,RelativeLayout 是最合適的選擇。步驟如下:
RelativeLayout 作為根容器,並指定 fill_parent 填滿整個視窗。關鍵屬性說明:
android:layout_alignParentTop="true",對齊父容器的頂端。android:layout_alignParentBottom="true",對齊父容器的底端。android:layout_below="@id/toppanel" 表示位於頂部元件下方;android:layout_above="@id/panelBottom" 表示位於底部元件上方。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:id="@+id/toppanel">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="用戶資訊表單(頂部)"
android:textSize="11pt" />
</RelativeLayout>
<RelativeLayout android:id="@+id/panelBottom"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content">
<Button
android:text="Save(底部元件)"
android:id="@+id/button1"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
</RelativeLayout>
<ScrollView
android:layout_below="@id/toppanel"
android:layout_above="@id/panelBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- 這裡放置中間部分的元件 -->
</ScrollView>
</RelativeLayout>
上述程式碼中:
RelativeLayout 命名為 toppanel。RelativeLayout 命名為 panelBottom。ScrollView 捲動視圖,好處是當子元件內容過長時會自動出現捲動條。接著在中間的 ScrollView 內加入一個 TableLayout 表格佈局,讓表單排列更整齊。
<TableLayout android:padding="3dip"
android:id="@+id/tableLayout1"
android:layout_width="fill_parent"
android:stretchColumns="1"
android:layout_height="fill_parent">
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="right"
android:padding="3dip"
android:text="User">
</TextView>
<EditText android:id="@+id/editText1"
android:padding="3dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></EditText>
</TableRow>
</TableLayout>
其中 android:stretchColumns="1" 讓第二欄(索引從 0 起算)自動伸展填滿剩餘空間,使得輸入框能佔滿整行,畫面更為美觀。
Android PreferenceActivity 詳解:用系統設定頁的架構做自己的設定介面
很多書對 PreferenceActivity 幾乎一筆帶過,但它在真實專案裡非常好用。本文把它的資料保存機制、建立方式、可用元素與事件回呼一次講完。 先看長相 左圖
Android 網絡連接處理:URL 連接、HttpClient 與 WebView 三種方案
Android 提供多種網絡編程方式,本文逐一說明各自的適用場景與關鍵設定。 方案一:URL + URLConnection/HttpURLConnection jav
Android 中使用 SAX 解析 XML 文件的完整實踐
為什麼選 SAX SAX 是一款解析速度快、內存佔用低的 XML 解析器,非常適合 Android 這類資源受限的移動設備。它採用事件驅動模式:並不需要把整份文檔讀進內存
Android JSON 解析實戰:從回應中取出你要的那幾個欄位
JSON(JavaScript Object Notation)早已成為應用程式之間交換資料的通用語言。相較於 XML,它沒有大量冗餘的封閉標籤,結構輕量、可讀性高,行動