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

Android 基本控制元件(上):Button 按鈕元件入門

編輯:關於 Android 程式設計

Button 的繼承結構

java.lang.Object
 → android.view.View
  → android.widget.TextView
   → android.widget.Button

這個繼承鏈說明了兩件事:Button 具備 View 的全部屬性與事件能力,同時因為繼承自 TextView,所以文字相關的設定(顏色、大小、內容)都能直接沿用。

一個最簡單的範例

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/mybut1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FF0000"
        android:textSize="12px"
        android:text="按鈕組件" />
</RelativeLayout>

逐行屬性說明

  • layout_width / layout_height 設為 wrap_content:寬高都依文字內容自動伸縮。
  • android:id="@+id/mybut1":定義元件的 id,供 Activity 以 findViewById 取得。
  • android:textColor="#FF0000":以 RGB 十六進位設定文字顏色,這裡是紅色。
  • android:textSize="12px":設定文字大小,px 是像素單位。
  • android:text="按鈕組件":設定按鈕上顯示的文字。

另外要留意父容器的設定:範例中 RelativeLayout 的寬高都是 fill_parent,也就是佔滿整個螢幕;若改成 LinearLayout 並設 android:orientation="vertical",多個元件就會垂直排列。

實際寫專案時,textSize 建議改用 sp 單位(例如 16sp),這樣才能跟著使用者的系統字級縮放偏好一起變,避免在視力需求不同的裝置上變得難以閱讀。

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