Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android Toast 用法:短暫提示訊息與自訂版面

Toast 是 Android 最輕量的提示機制:它會浮在畫面上短暫停留,然後自動消失,而且永遠不會取得焦點。這代表它不會打斷使用者正在做的事,也不會攔截觸控,因此很適合拿來回報「已複製」「已儲存」這類不影響操作的狀態。

最常見的一行寫法

Toast.makeText(MyClass.this, "note info", Toast.LENGTH_SHORT).show();

三個參數分別是 Context、要顯示的文字,以及顯示時長。時長只有兩個選項:Toast.LENGTH_SHORT 約兩秒、Toast.LENGTH_LONG 約三到四秒,系統會自行換算,你無法指定任意秒數。最後一定要呼叫 show(),否則什麼都不會出現。

自訂版面:圖片加文字

需要更豐富的呈現時,可以自己準備一個版面,透過 setView() 交給 Toast。以下這個方法示範了「圖片 + 一段訊息」的提示:

protected void showToast() {
    // 建立自訂的 view
    View view = inflateView(R.layout.incoming_message_panel);

    // 填入要顯示的文字
    TextView tv = (TextView) view.findViewById(R.id.message);
    tv.setText("khtx. meet u for dinner. cul8r");

    // 綁上 view 並顯示
    Toast toast = new Toast(this);
    toast.setView(view);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.show();
}

對應的版面檔 res/layout/incoming_message_panel.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/toast_frame">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/sample_thumb_2" />

        <TextView
            android:id="@+id/message"
            android:layout_gravity="center_vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="6dip" />

    </LinearLayout>
</FrameLayout>

這裡有兩個關鍵細節:背景使用系統內建的 @android:drawable/toast_frame,外觀才會和其他 Toast 一致;而 android:id="@+id/message" 就是你稍後在程式碼裡 findViewById 要對上的那個 id。

實務上要提醒的是,自訂 Toast 在較新的 Android 版本上會被系統改寫成文字樣式,因此它並不適合當作重要訊息的唯一出口。真正需要使用者確認的事情,請改用 Dialog 或 Snackbar;Toast 就讓它專心做那個「說完就退場」的角色。

Copyright © Linux教程網 All Rights Reserved