Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 入門教程(五):TextView 標籤的使用與文字顯示

編輯:Android 開發實例

寫完 HelloAndroid 之後,總覺得沒寫半行程式碼對不起自己。這一節就在它的基礎上,正式與 TextView 打交道:在版面中建立 TextView 物件、學會在 res/values/string.xml 裡定義字串常數,然後用兩種方式把文字顯示出來。

[執行結果圖]

做法一:全部交給 XML

畫面上那幾個字從哪裡來?先在 res/values/string.xml 加一行:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, HelloAndroid!</string>
    <string name="app_name">HelloAndroid</string>
    <string name="textView_text">歡迎來到魏祝林的部落格</string>
</resources>

接著在 main.xml 裡引用它,把原本的 @string/hello 換成 @string/textView_text:

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/textView_text" />
</LinearLayout>

執行之後畫面就會顯示那段歡迎語。對習慣寫程式的人來說,這種「一行 Java 都沒動」的做法反而有點不踏實——但這正是 Android 的設計意圖:靜態內容交給資源檔,職責分離。

做法二:在 Java 裡用 setText 改寫

先把 main.xml 回到原樣,只多補一個 id,讓 Java 端找得到這個物件:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

主程式 HelloAndroid.java:

package com.android.test;

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

public class HelloAndroid extends Activity {

    private TextView myTextView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 載入 main.xml,此時 myTextView 的文字是 hello
        setContentView(R.layout.main);

        // 用 id 找到這個 TextView 物件
        myTextView = (TextView) findViewById(R.id.myTextView);

        String welcome_mes = "歡迎來到魏祝林的部落格";
        // 用 setText 把文字換掉
        myTextView.setText(welcome_mes);
    }
}

該選哪一種?

兩種寫法效果相同,但建議優先用第一種:把字串放進資源檔,才能支援多語系與不同螢幕的字型調整;程式碼裡只處理「會變動」的文字(例如抓回來的資料、計算結果)。若文字在編譯期就確定,寫死在 Java 裡反而增加維護成本。

兩個重點:

  1. setContentView(R.layout.main) 表示載入 res/layout/main.xml 的內容並呈現在畫面上。
  2. myTextView = (TextView) findViewById(R.id.myTextView) 是在版面中找出 id 為 myTextView 的控件,並轉型為 TextView。

下一節我們來談 Android 的五大版面容器。

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