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

系出名門 Android(5):常用 View 元件巡禮——TextView、Button、ImageView 與時鐘元件

編輯:Android 開發教學

簡介

Android 的介面由各種 View 元件堆疊而成。本節整理開發中最常打交道的一批基礎元件:

TextView——文字顯示元件

Button——按鈕元件

ImageButton——圖片按鈕元件

ImageView——圖片顯示元件

CheckBox——核取方塊元件

RadioButton——單選按鈕元件

AnalogClock——模擬時鐘(帶指針與錶盤)元件

DigitalClock——數位時鐘元件

一、TextView 的 Demo

先用最簡單的 TextView 開個頭。版面配置檔 textview.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- TextView - 文字顯示元件 -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />

</LinearLayout>

對應的程式碼 _TextView.java:

package com.webabcd.view;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class _TextView extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.textview);

        // 設定 Activity 的標題
        setTitle("TextView");

        TextView txt = (TextView) this.findViewById(R.id.textView);

        // 設定文字內容,需要換行時使用 "\n"
        txt.setText("我是 TextView\n顯示文字用的");
    }
}

小結

這批元件都遵循同一套使用模式:先在 XML 版面檔中宣告外觀與初始屬性,再在 Activity 的 onCreate() 裡透過 findViewById() 取得參考,接著動態設定文字、圖片或監聽器。掌握這個流程,其餘元件的用法基本可以類推。

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