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

Android 桌面懸浮窗進階實作:還原 QQ 手機管家的小火箭加速動畫

編輯:關於 Android 程式設計

只要是 QQ 手機管家的老使用者,對那個「小火箭加速」應該都不陌生:把懸浮窗拖成一支小火箭,移到螢幕下方的發射台放手,火箭就呼嘯著衝出畫面。本文就在先前「模仿 360 手機衛士懸浮窗」的基礎上,把這個效果完整做出來。

整篇文章的重心放在火箭升空這段動畫,所以懸浮窗的基礎框架直接沿用舊有的程式碼。如果你還沒看過那篇基礎教學,建議先讀過再回來。

一、與其說是懸浮窗,不如說是兩個懸浮窗

相較於一般的桌面懸浮窗,這次多了兩個需求:拖曳時懸浮窗要變身成小火箭;螢幕底部要有一個火箭發射台。因此我們從發射台開始寫。

1. launcher.xml:發射台的版面

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/launcher_img"
        android:layout_width="200dp"
        android:layout_height="88dp"
        android:src="@drawable/launcher_bg_hold" />

</LinearLayout>

這裡的 ImageView 負責反映發射台目前的狀態。事先準備兩張圖:一張是火箭尚未靠近時的「待機」圖,一張是火箭已就位、隨時可以發射的「點火」圖。

2. RocketLauncher:發射台的 View

public class RocketLauncher extends LinearLayout {

    /** 發射台寬度 */
    public static int width;
    /** 發射台高度 */
    public static int height;

    private ImageView launcherImg;

    public RocketLauncher(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.launcher, this);
        launcherImg = (ImageView) findViewById(R.id.launcher_img);
        width = launcherImg.getLayoutParams().width;
        height = launcherImg.getLayoutParams().height;
    }

    /** 火箭被拖到發射台上時,切換為點火狀態 */
    public void updateLauncherStatus(boolean isReadyToLaunch) {
        if (isReadyToLaunch) {
            launcherImg.setImageResource(R.drawable.launcher_bg_fire);
        } else {
            launcherImg.setImageResource(R.drawable.launcher_bg_hold);
        }
    }
}

建構子中透過 LayoutInflater.inflate() 載入版面,並把寬高記錄下來,之後 MyWindowManager 要靠這兩個值來定位發射台。updateLauncherStatus() 則依傳入的旗標切換圖片。

二、改造 MyWindowManager

新增的檔案只有上面兩個,其餘都是修改既有程式碼。 manager 這邊主要補上發射台的建立、移除與更新,以及「火箭是否已就位」的判斷。

public class MyWindowManager {

    private static FloatWindowSmallView smallWindow;
    private static FloatWindowBigView bigWindow;
    private static RocketLauncher rocketLauncher;

    private static LayoutParams smallWindowParams;
    private static LayoutParams bigWindowParams;
    private static LayoutParams launcherParams;

    private static WindowManager mWindowManager;
    private static ActivityManager mActivityManager;

    /** 建立發射台,位置固定在螢幕底部水平居中 */
    public static void createLauncher(Context context) {
        WindowManager windowManager = getWindowManager(context);
        int screenWidth = windowManager.getDefaultDisplay().getWidth();
        int screenHeight = windowManager.getDefaultDisplay().getHeight();
        if (rocketLauncher == null) {
            rocketLauncher = new RocketLauncher(context);
            if (launcherParams == null) {
                launcherParams = new LayoutParams();
                launcherParams.x = screenWidth / 2 - RocketLauncher.width / 2;
                launcherParams.y = screenHeight - RocketLauncher.height;
                launcherParams.type = LayoutParams.TYPE_PHONE;
                launcherParams.format = PixelFormat.RGBA_8888;
                launcherParams.gravity = Gravity.LEFT | Gravity.TOP;
                launcherParams.width = RocketLauncher.width;
                launcherParams.height = RocketLauncher.height;
            }
            windowManager.addView(rocketLauncher, launcherParams);
        }
    }

    public static void removeLauncher(Context context) {
        if (rocketLauncher != null) {
            WindowManager windowManager = getWindowManager(context);
            windowManager.removeView(rocketLauncher);
            rocketLauncher = null;
        }
    }

    public static void updateLauncher() {
        if (rocketLauncher != null) {
            rocketLauncher.updateLauncherStatus(isReadyToLaunch());
        }
    }

    /**
     * 判斷小火箭是否已經拖到發射台上。
     * 做法就是檢查小火箭的矩形範圍與發射台的矩形範圍是否相交。
     */
    public static boolean isReadyToLaunch() {
        if ((smallWindowParams.x > launcherParams.x
                && smallWindowParams.x + smallWindowParams.width
                        < launcherParams.x + launcherParams.width)
                && (smallWindowParams.y + smallWindowParams.height > launcherParams.y)) {
            return true;
        }
        return false;
    }

    private static WindowManager getWindowManager(Context context) {
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
        }
        return mWindowManager;
    }
}

至于 createSmallWindow()、removeSmallWindow()、createBigWindow()、removeBigWindow() 以及內存百分比的計算邏輯,與基礎版本相同,這裡不再重複貼上。isReadyToLaunch() 是整段效果的關鍵:它並沒有做精細的碰撞偵測,只是拿小火箭的 x/y 範圍去和發射台比對,實測已經足夠順手。

三、FloatWindowSmallView:拖曳變身與升空動畫

public class FloatWindowSmallView extends LinearLayout {

    public static int windowViewWidth;
    public static int windowViewHeight;

    private static int statusBarHeight;

    private WindowManager windowManager;
    private LinearLayout smallWindowLayout;
    private ImageView rocketImg;
    private WindowManager.LayoutParams mParams;

    private float xInScreen, yInScreen;
    private float xDownInScreen, yDownInScreen;
    private float xInView, yInView;

    private int rocketWidth;
    private int rocketHeight;
    private boolean isPressed;

    public FloatWindowSmallView(Context context) {
        super(context);
        windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
        smallWindowLayout = (LinearLayout) findViewById(R.id.small_window_layout);
        windowViewWidth = smallWindowLayout.getLayoutParams().width;
        windowViewHeight = smallWindowLayout.getLayoutParams().height;
        rocketImg = (ImageView) findViewById(R.id.rocket_img);
        rocketWidth = rocketImg.getLayoutParams().width;
        rocketHeight = rocketImg.getLayoutParams().height;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isPressed = true;
                xInView = event.getX();
                yInView = event.getY();
                xDownInScreen = event.getRawX();
                yDownInScreen = event.getRawY() - getStatusBarHeight();
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                break;
            case MotionEvent.ACTION_MOVE:
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                updateViewStatus();
                updateViewPosition();
                break;
            case MotionEvent.ACTION_UP:
                isPressed = false;
                if (MyWindowManager.isReadyToLaunch()) {
                    launchRocket();
                } else {
                    updateViewStatus();
                    // 按下與放開位置相同,視為單擊
                    if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
                        openBigWindow();
                    }
                }
                break;
        }
        return true;
    }

    private void launchRocket() {
        MyWindowManager.removeLauncher(getContext());
        new LaunchTask().execute();
    }

    private void updateViewPosition() {
        mParams.x = (int) (xInScreen - xInView);
        mParams.y = (int) (yInScreen - yInView);
        windowManager.updateViewLayout(this, mParams);
        MyWindowManager.updateLauncher();
    }

    /** 拖曳中顯示小火箭,放手後還原成懸浮窗 */
    private void updateViewStatus() {
        if (isPressed && rocketImg.getVisibility() != View.VISIBLE) {
            mParams.width = rocketWidth;
            mParams.height = rocketHeight;
            windowManager.updateViewLayout(this, mParams);
            smallWindowLayout.setVisibility(View.GONE);
            rocketImg.setVisibility(View.VISIBLE);
            MyWindowManager.createLauncher(getContext());
        } else if (!isPressed) {
            mParams.width = windowViewWidth;
            mParams.height = windowViewHeight;
            windowManager.updateViewLayout(this, mParams);
            smallWindowLayout.setVisibility(View.VISIBLE);
            rocketImg.setVisibility(View.GONE);
            MyWindowManager.removeLauncher(getContext());
        }
    }

    private void openBigWindow() {
        MyWindowManager.createBigWindow(getContext());
        MyWindowManager.removeSmallWindow(getContext());
    }

    /** 火箭升空:在背景執行緒中不斷把 y 座標往上推 */
    class LaunchTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            while (mParams.y > 0) {
                mParams.y = mParams.y - 10;
                publishProgress();
                try {
                    Thread.sleep(8);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
        }

        @Override
        protected void onPostExecute(Void result) {
            updateViewStatus();
            mParams.x = (int) (xDownInScreen - xInView);
            mParams.y = (int) (yDownInScreen - yInView);
            windowManager.updateViewLayout(FloatWindowSmallView.this, mParams);
        }
    }
}

這裡多了一個 isPressed 旗標用來判斷使用者是否正在拖曳。拖曳時呼叫 updateViewStatus(),懸浮窗就變成小火箭;手指離開時同樣呼叫它,此時 isPressed 為 false,於是又還原成懸浮窗。

升空的動畫寫在 LaunchTask 裡:doInBackground() 每 8 毫秒把 y 座標往上推 10 像素,onProgressUpdate() 負責刷新畫面,y 歸零動畫結束,最後在 onPostExecute() 把懸浮窗放回原本位置。

四、別忘了權限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />

實際執行的流程是:在主介面點擊 Start Float Window 開啟懸浮窗並回到桌面,拖曳懸浮窗後它就變成小火箭,移到螢幕底部的發射台上放手,小火箭便一飛沖天。

伴隨著小火箭升空,這一年的最後一篇文章也劃下句點。新的一年即將開始,願大家在工作與課業上都能像這支小火箭一樣往上衝,抵達一個新的高度!

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