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

Android Toasts 提示訊息使用教學

編輯:關於 Android 程式設計

1. 基礎用法

Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show();

當然,也可以把方法串接起來,不必保留 Toast 物件:

Toast.makeText(context, text, duration).show();

2. 調整顯示位置

toast.setGravity(Gravity.TOP|Gravity.LEFT, x, y);

透過 setGravity 方法即可改變 Toast 的預設顯示位置。

3. 自訂 Toast

LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root)); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("This is a custom toast"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show();

自訂 Toast 時,透過 LayoutInflater 載入自訂佈局,再用 setView() 指定檢視,就能呈現自訂的提示樣式。

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