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

Android 學習筆記二十:Toast 吐司、Notification 通知與 PopupWindow 彈出視窗

編輯:關於 Android 程式設計

Toast 吐司

Toast 是我們日常開發中經常使用的元件。它是 Android 系統用來顯示訊息的一種機制,與 Dialog 不同,Toast 不會取得焦點,通常在顯示一段時間後便會自動消失。以下介紹 Toast 的幾種常見用法:

第一種,預設顯示方式,也是最常用的方式:

  Toast.makeText(MainActivity.this, "這是預設的顯示方式", Toast.LENGTH_SHORT).show(); 

第二種,自訂顯示位置的用法:

 Toast toast = Toast.makeText(MainActivity.this, "這是自訂顯示位置的效果", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER, 0, 0); toast.show(); 

第三種,帶圖片顯示:

  Toast toast = Toast.makeText(MainActivity.this, "這是帶圖片的效果", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER, 0, 0); LinearLayout linearLayout = (LinearLayout) toast.getView(); ImageView imageView = new ImageView(MainActivity.this); imageView.setImageResource(R.mipmap.ic_launcher); linearLayout.addView(imageView, 0); toast.show(); 

第四種,完全自訂顯示方式:

  LayoutInflater layoutInflater = getLayoutInflater(); View toastView = layoutInflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.ll_toast)); Toast toast = new Toast(MainActivity.this); toast.setDuration(Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(toastView); toast.show(); 

版面配置檔程式碼:

 <!--?xml version="1.0" encoding="utf-8"?--> <LinearLayout android:gravity="center" android:id="@+id/ll_toast" android:layout_height="match_parent" android:layout_marginLeft="16sp" android:layout_marginTop="16sp" android:layout_width="match_parent" android:orientation="horizontal" xmlns:android="https://schemas.android.com/apk/res/android"> <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@mipmap/ic_launcher"> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="這是完全自訂的吐司" android:textSize="20sp"> </TextView> </ImageView> </LinearLayout> 

第五種,其他執行緒透過 handler 顯示:

 new Thread(new Runnable() { @Override public void run() { handler.sendEmptyMessage(1); } }).start(); public void showToast() { Toast.makeText(MainActivity.this, "這是來自其它執行緒的吐司", Toast.LENGTH_SHORT).show(); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { showToast(); } super.handleMessage(msg); } }; 

實現效果圖:

最後附上 Toast 的國內鏡像 API。

Notification 通知

Notification 是一種具有全域效果的通知,程式通常透過 NotificationManager 服務來發送。在 Android API 3.0 之前,建議使用 Notification.Builder 來建構訊息;而在 3.0 之後,則建議改用 NotificationCompat.Builder 建構。

以下介紹 Notification 的基本用法。它主要牽涉到兩個類別:

Notification 類別:通知訊息類,用於承載通知的內容。我們一般不直接建構這個物件,而是使用其內部類別 NotificationCompat.Builder 來實例化(Android 3.0 以下使用 Notification.Builder),設定好各種屬性後,再透過 build() 方法取得一個 Notification 物件,最後用 NotificationManager.notify() 發送通知。

NotificationManager 類別:通知管理器類,是由系統維護的服務,以單例模式取得,因此一般不直接實例化。在 Activity 中,只要傳入 Context.NOTIFICATION_SERVICE,就能透過 getSystemService(String) 方法取得 NotificationManager 物件。

通知設定的相關方法:

setContentTitle(CharSequence):設定標題,必須設定
setContentText(CharSequence):設定內容,必須設定
setSmallIcon(int):設定接收到通知時頂部顯示的小圖示,必須設定
setSubText(CharSequence):設定內容下方一小行的文字
setTicker(CharSequence):設定收到通知時在頂部顯示的文字訊息
setLargeIcon(Bitmap):設定大圖示
setAutoCancel(boolean):設定使用者點擊通知後是否取消通知(預設不取消)
setDefaults(int):以最簡單的方式為通知加入聲音、閃燈與震動效果,可組合多個屬性,例如 Notification.DEFAULT_VIBRATE(預設震動)、DEFAULT_SOUND(預設聲音)、DEFAULT_LIGHTS(預設三色燈)、DEFAULT_ALL(以上三種全部)
setVibrate(long[]):設定震動方式
setLights(int argb, int onMs, int offMs):設定三色燈,參數依序為燈光顏色、亮持續時間、暗持續時間
setSound(Uri):設定接收通知時的鈴聲,可用系統的也可自訂
setOngoing(boolean):設為 true 表示這是一個正在進行的通知
setProgress(int, int, boolean):設定帶進度條的通知,參數依序為進度條最大值、目前進度、進度是否不確定
setContentIntent(PendingIntent):PendingIntent 與 Intent 略有不同,可設定執行次數,主要用於遠端服務通信、鬧鐘、通知、啟動器、簡訊等場景
setPriority(int):設定優先級

使用 Notification 的步驟:

第一步:取得一個 NotificationManager 物件。
第二步:建立一個通知欄的 Builder 構造類。
第三步:對 Builder 進行相關設定,使用上面介紹的相關方法。
第四步:呼叫 Builder 的 build() 方法為 notification 賦值。
第五步:呼叫 NotificationManager 的 notify() 方法發送通知。

注意:Android 系統提供兩種取消通知的方式。一種由 Notification 自己維護,透過 setAutoCancel() 設定是否維護,傳入一個 boolean 值;另一種則由 NotificationManager 通知管理器維護,它透過 notify() 發送通知時所指定的通知標識 Id 來操作,可用 cancel(int) 移除指定通知,也可用 cancelAll() 移除所有通知。

以下透過一個簡單範例來體驗 Notification 的用法:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this; btn_default_notification = (Button) findViewById(R.id.btn_default_notification); btn_default_notification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(mContext, DefaultActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0); NotificationManager notificationManager = (NotificationManager) MainActivity.this.getSystemService(NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder(MainActivity.this); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentTitle("預設消息通知"); builder.setContentText("我是預設顯示的消息,我進來了"); builder.setWhen(System.currentTimeMillis()); builder.setTicker("接受到一條信息"); builder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE); builder.setAutoCancel(true); builder.setContentIntent(pendingIntent); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { Notification notification = builder.build(); notificationManager.notify(NOTIFICATION, notification); } } }); }

這裡只列出 Java 程式碼,其餘設定較為簡單就不再贅述。照例附上 Notification 的國內鏡像 API。

PopupWindow 彈出視窗

PopupWindow 這個類別用來實現一個彈出框,它可以載入任意內容的 View,並懸浮在當前 Activity 之上。一旦 PopupWindow 顯示出來,除了 Home 鍵之外的所有事件都會被它攔截。舉例來說,若一個 PopupWindow 彈出,你需要先點擊返回鍵讓它消失,Activity 才會跟著退出。

以下透過一個範例來體驗 PopupWindow:

Activity 程式碼:

 package com.example.popupwindow; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.PopupWindow; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Button btn_show_pop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_show_pop = (Button) findViewById(R.id.btn_show_pop); btn_show_pop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { initPop(view); } }); } private void initPop(View view) { View popView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_custom, null); Button btn_01 = (Button) popView.findViewById(R.id.btn_01); Button btn_02 = (Button) popView.findViewById(R.id.btn_02); Button btn_03 = (Button) popView.findViewById(R.id.btn_03); // 初始化一個 PopupWindow,第一個參數是加載的 View,第二個參數是 View 的寬度,第三個參數是 View 的高度,第四個是是否獲取焦點 final PopupWindow popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); // 設置加載動畫 popupWindow.setAnimationStyle(R.anim.pop_anim); // 設置可以點擊空白處讓 PopupWindow 消失 popupWindow.setOutsideTouchable(true); popupWindow.setTouchable(true); popupWindow.setTouchInterceptor(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { System.out.println("touch"); // 這裡如果返回 true 的話,touch 事件將被攔截 return false; } }); // 設置背景顏色 popupWindow.setBackgroundDrawable(new ColorDrawable(0x00ff0000)); // 設置 PopupWindow 顯示的位置,第一個參數是相對的 View,第二個是 X 軸,第三個參數是 Y 軸 // showAsDropDown(View anchor):相對某個控件的位置(正左下方),無偏移 // showAsDropDown(View anchor, int xoff, int yoff):相對某個控件的位置,有偏移 // showAtLocation(View parent, int gravity, int x, int y):相對於父控件的位置(例如正中央 Gravity.CENTER,下方 Gravity.BOTTOM 等),可設置偏移或無偏移 // PS:parent 這個參數只要是 activity 中的 view 就可以了! popupWindow.showAsDropDown(view, 40, 0); btn_01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "你點擊了水果", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); } }); btn_02.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "你點擊了運動", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); } }); btn_03.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(MainActivity.this, "你點擊了吃飯", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); } }); } }

版面配置檔程式碼:

 <!--?xml version="1.0" encoding="utf-8"?--> <LinearLayout android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical" xmlns:android="https://schemas.android.com/apk/res/android"> <Button android:id="@+id/btn_01" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="水果"> </Button> <Button android:id="@+id/btn_02" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_width="match_parent" android:text="運動"> </Button> <Button android:id="@+id/btn_03" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_width="match_parent" android:text="吃飯"> </Button> </LinearLayout>

實現效果:

其中,PopupWindow 共有九種構造方法,如下圖所示:

我們常用的有以下幾種:

 public PopupWindow (Context context) public PopupWindow(View contentView, int width, int height) public PopupWindow(View contentView) public PopupWindow(View contentView, int width, int height, boolean focusable) 

 

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