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

Android 自定義 PopupWindow 實戰:寬高獲取、三種定位與進出動畫

編輯:關於 Android 程式設計

自定義 PopupWindow 本身並不難,真正麻煩的是兩件事:定位與動畫。定位之所以棘手,是因為它牽扯到一個矛盾——彈窗還沒 show 出來就拿不到寬高,可定位又偏偏需要寬高。本文把這個死結拆開,並附上「下左、下中、下右」三種常用定位寫法與一組進出動畫。


先解決寬高:強制繪製一次

思路並不複雜:在初始化階段對 contentView 手動觸發一次 measure,就能提前拿到測量後的尺寸,而不必等到真正顯示。

// 用於保存 PopupWindow 的寬度
private int width;
// 用於保存 PopupWindow 的高度
private int height;

public CustomPopupWindow(Activity activity) {
    super(activity);
    this.activity = activity;
    this.initPopupWindow();
}

private void initPopupWindow() {
    LayoutInflater inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.contentView = inflater.inflate(R.layout.popupwindow_custom, null);
    this.setContentView(contentView);

    this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
    this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

    this.setTouchable(true);
    this.setFocusable(true);
    this.setOutsideTouchable(true);

    // 設定彈出視窗動畫
    this.setAnimationStyle(R.style.PopupAnimation);

    // 半透明背景,讓點擊外部可感知
    ColorDrawable background = new ColorDrawable(0x4f000000);
    this.setBackgroundDrawable(background);

    this.mandatoryDraw();
}

/** 強制繪製 contentView,並快取它的尺寸 */
private void mandatoryDraw() {
    this.contentView.measure(
            View.MeasureSpec.UNSPECIFIED,
            View.MeasureSpec.UNSPECIFIED);
    this.width = this.contentView.getMeasuredWidth();
    this.height = this.contentView.getMeasuredHeight();
}

定位:相對於目標 View 的三種擺放

核心 API 是 showAtLocation(),配合 parent.getLocationOnScreen() 取得目標 View 在螢幕中的絕對座標,再做加減法即可。

顯示在目標 View 的左下方

public void showAtDropDownLeft(View parent) {
    if (parent.getVisibility() == View.GONE) {
        this.showAtLocation(parent, 0, 0, 0);
    } else {
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0],
                location[1] + parent.getHeight());
    }
}

顯示在目標 View 的中央下方

public void showAtDropDownCenter(View parent) {
    if (parent.getVisibility() == View.GONE) {
        this.showAtLocation(parent, 0, 0, 0);
    } else {
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0] / 2 + parent.getWidth() / 2 - this.width / 2,
                location[1] + parent.getHeight());
    }
}

顯示在目標 View 的右下方

public void showAtDropDownRight(View parent) {
    if (parent.getVisibility() == View.GONE) {
        this.showAtLocation(parent, 0, 0, 0);
    } else {
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0] + parent.getWidth() - this.width,
                location[1] + parent.getHeight());
    }
}

這裡之所以必須先拿到 this.width,正是前面 mandatoryDraw() 的價值所在。


動畫:從右上角展開、往右上角收起

styles.xml

<style name="PopupAnimation" parent="android:Animation">
    <item name="android:windowEnterAnimation">@anim/popwindow_in</item>
    <item name="android:windowExitAnimation">@anim/popwindow_out</item>
</style>

popwindow_in.xml——縮放由 0 到 1,透明度由全透明到不透明,pivot 設在右上角,因此视觉上是由右上角長出來。

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator">
    <scale android:duration="200"
        android:fromXScale="0.0" android:fromYScale="0.0"
        android:pivotX="100%" android:pivotY="0%"
        android:toXScale="1.0" android:toYScale="1.0" />
    <alpha android:duration="200"
        android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>

popwindow_out.xml——完全相反的過程。

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/decelerate_interpolator">
    <scale android:duration="200"
        android:fromXScale="1.0" android:fromYScale="1.0"
        android:pivotX="100%" android:pivotY="0%"
        android:toXScale="0.0" android:toYScale="0.0" />
    <alpha android:duration="200"
        android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>

組裝:加上一個簡單的 Builder

把上述能力收攏到一個類裡,再用建造者模式對外暴露少量可配置項,呼叫端會乾淨很多。

public class CustomPopupWindow extends android.widget.PopupWindow {

    private Activity activity;
    private View contentView;
    private int width;
    private int height;

    public CustomPopupWindow(Activity activity) {
        super(activity);
        this.activity = activity;
        this.initPopupWindow();
    }

    private void initPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.contentView = inflater.inflate(R.layout.popupwindow_custom, null);
        this.setContentView(contentView);
        this.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setTouchable(true);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.setAnimationStyle(R.style.PopupAnimation);
        this.setBackgroundDrawable(new ColorDrawable(0x4f000000));
        this.mandatoryDraw();
    }

    private void mandatoryDraw() {
        this.contentView.measure(
                View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        this.width = this.contentView.getMeasuredWidth();
        this.height = this.contentView.getMeasuredHeight();
    }

    public void showAtDropDownLeft(View parent) {
        if (parent.getVisibility() == View.GONE) {
            this.showAtLocation(parent, 0, 0, 0);
            return;
        }
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0], location[1] + parent.getHeight());
    }

    public void showAtDropDownCenter(View parent) {
        if (parent.getVisibility() == View.GONE) {
            this.showAtLocation(parent, 0, 0, 0);
            return;
        }
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0] / 2 + parent.getWidth() / 2 - this.width / 2,
                location[1] + parent.getHeight());
    }

    public void showAtDropDownRight(View parent) {
        if (parent.getVisibility() == View.GONE) {
            this.showAtLocation(parent, 0, 0, 0);
            return;
        }
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        this.showAtLocation(parent, 0,
                location[0] + parent.getWidth() - this.width,
                location[1] + parent.getHeight());
    }

    public static class PopupWindowBuilder {
        private static String activityHashCode;
        private static CustomPopupWindow popupWindow;
        public static PopupWindowBuilder ourInstance;

        public static PopupWindowBuilder getInstance(Activity activity) {
            if (ourInstance == null) {
                ourInstance = new PopupWindowBuilder();
            }
            String hashCode = String.valueOf(activity.hashCode());
            // 換了 Activity 就重建一份,避免持有舊的 Context
            if (!hashCode.equals(String.valueOf(activityHashCode))) {
                activityHashCode = hashCode;
                popupWindow = new CustomPopupWindow(activity);
            }
            return ourInstance;
        }

        public PopupWindowBuilder setTouchable(boolean touchable) {
            popupWindow.setTouchable(touchable);
            return this;
        }

        public PopupWindowBuilder setAnimationStyle(int animationStyle) {
            popupWindow.setAnimationStyle(animationStyle);
            return this;
        }

        public PopupWindowBuilder setBackgroundDrawable(Drawable background) {
            popupWindow.setBackgroundDrawable(background);
            return this;
        }

        public CustomPopupWindow getPopupWindow() {
            popupWindow.update();
            return popupWindow;
        }
    }
}

效果

小結一下:寬高問題靠強制 measure 化解,定位問題靠 getLocationOnScreen 加上尺寸補償,動畫則交給 windowEnterAnimation 與 windowExitAnimation。三者拼起來,一個順手好用的彈窗元件就完成了。

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