編輯:Android 開發實例
寫完 HelloAndroid 之後,總覺得沒寫半行程式碼對不起自己。這一節就在它的基礎上,正式與 TextView 打交道:在版面中建立 TextView 物件、學會在 res/values/string.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 的設計意圖:靜態內容交給資源檔,職責分離。
先把 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 裡反而增加維護成本。
兩個重點:
setContentView(R.layout.main) 表示載入 res/layout/main.xml 的內容並呈現在畫面上。myTextView = (TextView) findViewById(R.id.myTextView) 是在版面中找出 id 為 myTextView 的控件,並轉型為 TextView。下一節我們來談 Android 的五大版面容器。
自製 TabMenu 彈出選單:封裝成可重複使用的複合控件
用過 UC 瀏覽器 Android 版的人,大概都對它那個分頁式選單有印象。Android 原生的 OptionsMenu 有個先天限制:超過六項就被折進「更多」裡,能呈
Android MediaPlayer 音訊播放:播放、暫停與快轉
MediaPlayer 是 Android 中常用的多媒體播放類別。除了基本的播放與暫停,也可以透過 seekTo() 實作快轉與快退。 初始化播放器 MediaPlay
Android 學習筆記(二):手把手實現電話撥號器
如今 Android 已經在智能手機市場佔據了強大的霸主地位,也吸引了越來越多的開發者。本文將以一個電話撥號器為例,帶領大家一步步完成一個簡單實用的 App。 一、新建項
Android JSON 解析器:用 JSONObject 讀取天氣資料
為什麼 JSON 在 Android 中很重要 JSON 是一種輕量、易讀的資料交換格式,常用於 API 回傳。相較 XML,它結構更簡潔,解析也相對直接。Android