用過 iPhone 的人都知道那個圓球輔助工具 AssistiveTouch:它浮在整個系統介面之上,可以拖到任何位置。本文模擬它做一個小案例,重點是還原那顆可拖動、點擊後彈出選單的浮球。
拖動小圓球:
點擊彈出 popup 視窗:
要讓浮球一直懸浮在視窗最上層,做法是:程式初始化時啟動一個 Service,在它的 onCreate() 中用 LayoutInflater 載入浮球布局 floatball.xml,並為該 view 掛上 click 監聽;收到點擊事件後建立一個 PopupWindow 彈出選單。整體架構就是這樣。
而實現「懸浮於最前面」的關鍵屬性只有一個:WindowManager.LayoutParams.TYPE_PHONE。把 WindowManager.LayoutParams 的 type 設為這個值,view 就會浮在最上層。
package com.tyd.floatball.util;
import android.app.Application;
import android.view.WindowManager;
public class MyApplication extends Application {
private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
public WindowManager.LayoutParams getMywmParams() {
return wmParams;
}
}
把 LayoutParams 放在 Application 中統一持有,各處要調整浮球位置或尺寸時就不必反覆重建物件。實作時另外要記得在 Service 中透過 WindowManager 的 addView 把浮球掛上去,並在 onDestroy 中呼叫 removeView,否則 Service 結束後會留下無法移除的殘影;同時别忘了 SYSTEM_ALERT_WINDOW 權限與較新系統上的「顯示在其他應用程式上層」授權引導。