編輯:Android 技術基礎
Toast 大概是 Android 裡最熟悉的元件:它浮在畫面最上層,幾秒後自動消失,不搶焦點、也不打斷使用者操作。正因為太熟悉,多數人只會用 Toast.makeText(...).show() 這一招。事實上,Toast 還能帶上圖示、能指定出現在螢幕的哪個角落、能換成完全自訂的版面,甚至能從子執行緒中彈出來。
本章就安排五顆按鈕,把 Toast 的五種玩法一次跑過。
Toast 與 Dialog 最大的差別在於「焦點」:Dialog 會搶走焦點、要求使用者先回應;Toast 不會。它的顯示時間由系統控制(LENGTH_SHORT 約兩秒、LENGTH_LONG 約三到四秒),時間到就自己消失,無法像 Dialog 那樣一直停在畫面上。因此 Toast 適合放「操作成功」「已複製」「網路不穩」這類不需要使用者回答的訊息。
開啟 res/layout/activity_main.xml,從工具欄拖入 5 個 Button。

切換到 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"
android:padding="5dip"
android:gravity="center">
<Button
android:id="@+id/original"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="預設樣式" />
<Button
android:id="@+id/byphoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="帶圖片樣式" />
<Button
android:id="@+id/customposition"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自訂顯示位置" />
<Button
android:id="@+id/alldiy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="完全自訂樣式" />
<Button
android:id="@+id/bythread"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="來自其他執行緒" />
</LinearLayout>
新增 res/layout/custom.xml,做成「標題列 + 內容區」的兩層結構:外層負責白底與外框,內層放一張圖片和一段說明文字。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/customtoast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffffff">
<TextView
android:id="@+id/titletoast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dip"
android:background="#16ccdd"
android:gravity="center"
android:textColor="#ffffffff" />
<LinearLayout
android:id="@+id/customtoastcontent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dip"
android:layout_marginRight="1dip"
android:layout_marginBottom="1dip"
android:orientation="vertical"
android:padding="15dip"
android:background="#ccffff">
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="@+id/prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:textColor="#ff000000" />
</LinearLayout>
</LinearLayout>
開啟 src/com.genwoxue.toast/MainActivity.java:
package com.genwoxue.toast;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Handler handler = new Handler();
private Button btnOriginal, btnByPhoto, btnCustomPosition, btnAllDiy, btnThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOriginal = (Button) findViewById(R.id.original);
btnByPhoto = (Button) findViewById(R.id.byphoto);
btnCustomPosition = (Button) findViewById(R.id.customposition);
btnAllDiy = (Button) findViewById(R.id.alldiy);
btnThread = (Button) findViewById(R.id.bythread);
btnOriginal.setOnClickListener(this);
btnByPhoto.setOnClickListener(this);
btnCustomPosition.setOnClickListener(this);
btnAllDiy.setOnClickListener(this);
btnThread.setOnClickListener(this);
}
/** 子執行緒不能直接操作 UI,必須用 Handler 把訊息丟回主執行緒 */
private void showToastFromThread() {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "我來自其他執行緒!",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onClick(View v) {
int id = v.getId();
// 1. 預設樣式:一行文字,最簡單
if (id == R.id.original) {
Toast.makeText(this, "預設 Toast 樣式", Toast.LENGTH_SHORT).show();
}
// 2. 帶圖片:拿到 Toast 內部的 LinearLayout,再塞一個 ImageView 進去
else if (id == R.id.byphoto) {
Toast toast = Toast.makeText(this, "帶圖片的 Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView image = new ImageView(this);
image.setImageResource(R.drawable.ic_launcher);
toastView.addView(image, 0); // 加到最前面
toast.show();
}
// 3. 只改位置:setGravity 決定貼在哪個邊
else if (id == R.id.customposition) {
Toast toast = Toast.makeText(this, "自訂位置 Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
// 4. 完全自訂:用 LayoutInflater 把 XML 變成 View,再交給 Toast
else if (id == R.id.alldiy) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom, null);
((ImageView) layout.findViewById(R.id.picture))
.setImageResource(R.drawable.ic_launcher);
((TextView) layout.findViewById(R.id.titletoast))
.setText("完全自訂 Toast");
((TextView) layout.findViewById(R.id.prompt))
.setText("顯示提示資訊……");
Toast toast = new Toast(this);
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
// 5. 從子執行緒發出
else if (id == R.id.bythread) {
new Thread(new Runnable() {
@Override
public void run() {
showToastFromThread();
}
}).start();
}
}
}
setContentView 與 inflate 的差別。 setContentView() 一旦被呼叫,版面就會立刻被掛到 Activity 上顯示出來;而 inflate() 只是把 XML 資源「充氣」成一個 View 物件,並不會顯示。當你需要在非 Activity 的場合(例如 Toast、Dialog、列表項)動態取得一份版面,就得靠 LayoutInflater。
Toast 只能用 new Toast 才能任意指定版面。 Toast.makeText() 回傳的是系統預設的單行文字樣式,想放圖片只能像範例那樣,從 toast.getView() 取出它的容器再加工。
子執行緒要切回主執行緒。 Android 的 UI 元件只能在主執行緒操作,所以背景執行緒裡必須透過 Handler.post()、runOnUiThread() 或 View.post() 把呼叫排回主執行緒,否則會直接拋出例外。
不建议用 switch 判斷 R.id。 新版建置工具下,R.id.xxx 不再是編譯期常數,switch 往往過不了編譯,改用 if / else if 才是保險做法——上面範例已經改成這種寫法。





EditText 輸入框詳解:從提示文本到自定義清空按鈕
本節引言: 上一節我們學了第一個 UI 控件 TextView(文本框),列舉了不少實際開發中會遇到的需求解法。這一節來學習第二個常用控件 EditText(輸入框)。它
Android 佈局教學:FrameLayout 框架佈局的特性與限制
FrameLayout 好比在螢幕上預留的一塊空白區域,你把元素填進去就好。它的個性非常鮮明:所有子元素都被放在區域的左上角,而且無法為它們指定確切座標;一旦有多個元素,
百度地圖 SDK 上手:從申請密鑰到畫出第一張地圖(從零開始學 Android)
地圖曾經是導航機的專利,智慧型手機普及之後,它變成了幾乎每支手機的標準配備,Google、百度、高德、凱立德之間的競爭也進入白熱化。對開發者而言好消息是:各家地圖服務商相
Paint API 之 PathEffect(路徑效果)詳解
本節引言: 本節繼續學習 Paint 的 API——PathEffect(路徑效果)。把畫筆的 style 設為 Stroke,我們就能繪製由線構成的圖形,但這些線偶爾會