完成 Android 開發環境搭建後,專案的基本結構與其他 Java 工程(如 SSH、Servlet 專案)並無二致,皆採用 Java 與 XML 檔案結合的方式構建工程。有幾個核心檔案必須熟悉:
R.layout.activity_main 等常數引用資源。預設的 HelloWorld 專案僅在左上角顯示文字。我們將修改佈局與資源,使文字置中於螢幕並自訂樣式。
將根佈局設為 RelativeLayout,並讓 TextView 填滿螢幕、垂直置中:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello_world" />
</RelativeLayout>
關鍵屬性解析:
android:layout_width="fill_parent" 與 android:layout_height="fill_parent":讓 TextView 佔滿整個螢幕空間。android:gravity="center_vertical":在該控件佔據的空間內垂直置中文字。注意:Android 4.0+ 建議使用 gravity 而非 layout_gravity。找到 <string name="hello_world"> 標籤,修改為想要顯示的文字。同樣可修改 app_name 將應用名稱漢化為「你好,世界」。
在 styles.xml 中新增 text_style 樣式,設定字體大小、顏色、粗體:
<style name="text_style">
<item name="android:textSize">24sp</item>
<item name="android:textColor">#ff0000</item>
<item name="android:textStyle">bold</item>
</style>
注意:Android 單位使用 sp(scale-independent pixels)而非 px,可確保文字在不同螢幕密度裝置上顯示一致。
接著在 activity_main.xml 的 TextView 中套用:style="@style/text_style"。
透過修改 XML 佈局、字串資源與樣式資源,我們在不動 Java 程式碼的情況下,完成了 UI 的調整與美化。這體現了 Android 「介面與邏輯分離」的設計理念,也為後續的國際化與多螢幕適配奠定基礎。