Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 靈活佈局:用 XML 檔取代拖拉排版

編輯:關於 Android 程式設計

一開始接觸 Android 時,我只會用拖拉的方式排版,既死板又難看。後來才發現,原來它和 JSP 一樣,可以靈活地使用 XML 檔來定義佈局,效果立刻大為改善。

話不多說,直接上例子。任何佈局既可以透過程式碼實作,也可以在 XML 中完成。以下用 XML 實作一個簡單的表單佈局。

首先在 src 中:

接著在 layout 目錄下新建 test_layout.xml:

<?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="vertical" >

    <TextView
        android:text="ceshi"
        android:id="@+id/layoutTextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff" >
    </TextView>

    <EditText
        android:text=""
        android:id="@+id/EditText01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:text="test"
        android:id="@+id/layoutButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

透過 XML 定義佈局,不僅結構一目了然,還能輕鬆調整元件的屬性與排列,遠比純粹用程式碼硬寫來得靈活。這正是 Android 開發中推薦使用 XML 佈局的核心原因。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved