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

仿 QQ 空間的 PopupWindow:依據點擊位置自動朝上或朝下彈出

編輯:關於 Android 開發

要做出的效果

打開 QQ 空間時有個箭頭按鈕,點下去會彈出一個 PopupWindow,而且它會依按鈕在畫面上的位置,自動決定顯示在箭頭上方還是下方。這比一律彈在螢幕正中央的做法自然得多。

拆解成四個步驟

  1. 自訂 PopupWindow,還原圖中的樣式(含上下兩個箭頭)。
  2. 取得被點擊按鈕的位置,判斷它在螢幕上半部還是下半部,決定朝上或朝下彈。
  3. 處理適配:操作列表是動態資料,需要自訂 ListView 並正確計算高度。
  4. 加上彈出/消失動畫與背景變暗。

步驟一:重寫 ListView 的高度計算

動態列表若交給系統自行測量,在 PopupWindow 這種 WRAP_CONTENT 的容器裡常常只顯示一行。重寫 onMeasure 給它一個足夠大的上限即可(這個技巧同樣能解掉 ScrollView 內嵌 ListView 只顯示一行的老問題):

public class MyListView extends ListView {
    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyListView(Context context) {
        super(context);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,
                MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST));
    }
}

步驟二:PopupWindow 的版面檔

上下兩個箭頭加上中間的列表,箭頭用 visibility 切換:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="right">

    <ImageView
        android:id="@+id/arrow_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="28dp"
        android:src="@drawable/arrow_up_white"
        android:visibility="visible" />

    <com.widget.MyListView
        android:id="@+id/lv_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/normal_margin8"
        android:layout_marginTop="-1dp"
        android:layout_marginBottom="-1dp"
        android:dividerHeight="0dp"
        android:layout_marginLeft="@dimen/normal_margin8"
        android:layout_marginRight="@dimen/normal_margin8"
        android:scrollbars="none"
        android:background="@drawable/custom_white"
        android:divider="@null"></com.widget.MyListView>

    <ImageView
        android:id="@+id/arrow_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="28dp"
        android:src="@drawable/arrow_down_white"
        android:visibility="visible" />
</LinearLayout>

步驟三:動畫資源

向下彈出用 popshow_operation_anim_down.xml,以箭頭為原點做放大:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <scale android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:pivotX="90%"
        android:pivotY="0%"
        android:fillAfter="false"
        android:duration="300" />
</set>

向上彈出用 popshow_operation_anim_up.xml,差別只在 pivotY 改成 100%:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <scale android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="0.0"
        android:toXScale="1.0"
        android:fromYScale="0.0"
        android:toYScale="1.0"
        android:pivotX="90%"
        android:pivotY="100%"
        android:fillAfter="false"
        android:duration="250" />
</set>

消失動畫用漸隱(alpha)即可,寫法同理。

步驟四:自訂 PopupWindow

public class CustomOperationPopWindow extends PopupWindow {
    private Context context;
    private View conentView;
    private View backgroundView;
    private Animation anim_backgroundView;
    private MyListView listView;
    private TypeSelectPopuAdapter selectAdapter;
    ImageView arrow_up, arrow_down;
    List<TypeSelect> typeSelectlist = new ArrayList<>();
    int[] location = new int[2];
    private OnItemListener onItemListener;

    public interface OnItemListener {
        void OnItemListener(int position, TypeSelect typeSelect);
    }

    public void setOnItemMyListener(OnItemListener onItemListener) {
        this.onItemListener = onItemListener;
    }

    public CustomOperationPopWindow(Context context) {
        this.context = context;
        initView();
    }

    public CustomOperationPopWindow(Context context, List<TypeSelect> typeSelectlist) {
        this.context = context;
        this.typeSelectlist = typeSelectlist;
        initView();
    }

    private void initView() {
        this.anim_backgroundView = AnimationUtils.loadAnimation(context, R.anim.alpha_show_anim);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.conentView = inflater.inflate(R.layout.view_operation_popupwindow, null);
        this.setContentView(conentView);
        this.setWidth(LayoutParams.MATCH_PARENT);
        this.setHeight(LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.update();

        // 半透明的 ColorDrawable,必須設定才能觸發 OnDismissListener
        ColorDrawable dw = new ColorDrawable(0000000000);
        this.setBackgroundDrawable(dw);
        this.setAnimationStyle(R.style.operation_popwindow_anim_style_up);

        this.listView = (MyListView) conentView.findViewById(R.id.lv_list);
        this.arrow_up = (ImageView) conentView.findViewById(R.id.arrow_up);
        this.arrow_down = (ImageView) conentView.findViewById(R.id.arrow_down);

        this.selectAdapter = new TypeSelectPopuAdapter(context, typeSelectlist,
                R.layout.item_operation_popu);
        this.listView.setAdapter(selectAdapter);
        this.listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isShowing()) {
                    dismiss();
                }
                onItemListener.OnItemListener(position, typeSelectlist.get(position));
            }
        });
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                if (backgroundView != null) {
                    backgroundView.setVisibility(View.GONE);
                }
            }
        });
    }

    public void setDataSource(List<TypeSelect> typeSelectlist) {
        this.typeSelectlist = typeSelectlist;
        this.selectAdapter.notifyDataSetChanged();
    }

    /** 不帶半透明背景,直接顯示 */
    public void showPopupWindow(View v) {
        v.getLocationOnScreen(location);   // 取得控制項的螢幕座標
        conentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        if (location[1] > MainApplication.SCREEN_H / 2 + 100) {
            // 按鈕在螢幕下半部 → 朝上彈
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_up);
            arrow_up.setVisibility(View.GONE);
            arrow_down.setVisibility(View.VISIBLE);
            this.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
                    location[1] - conentView.getMeasuredHeight());
        } else {
            // 按鈕在螢幕上半部 → 朝下彈
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_down);
            arrow_up.setVisibility(View.VISIBLE);
            arrow_down.setVisibility(View.GONE);
            this.showAsDropDown(v, 0, 0);
        }
    }

    /** 帶半透明背景 */
    public void showPopupWindow(View v, View backgroundView) {
        this.backgroundView = backgroundView;
        v.getLocationOnScreen(location);
        conentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        backgroundView.setVisibility(View.VISIBLE);
        backgroundView.startAnimation(anim_backgroundView);

        if (location[1] > MainApplication.SCREEN_H / 2 + 100) {
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_up);
            arrow_up.setVisibility(View.GONE);
            arrow_down.setVisibility(View.VISIBLE);
            this.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
                    location[1] - conentView.getMeasuredHeight());
        } else {
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_down);
            arrow_up.setVisibility(View.VISIBLE);
            arrow_down.setVisibility(View.GONE);
            this.showAsDropDown(v, 0, 0);
        }
    }

    /** 帶背景且可微調高度偏移 */
    public void showPopupWindow(View v, View backgroundView, int hight) {
        this.backgroundView = backgroundView;
        v.getLocationOnScreen(location);
        conentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        backgroundView.setVisibility(View.VISIBLE);
        backgroundView.startAnimation(anim_backgroundView);

        if (location[1] > MainApplication.SCREEN_H / 2 + 100) {
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_up);
            arrow_up.setVisibility(View.GONE);
            arrow_down.setVisibility(View.VISIBLE);
            this.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
                    location[1] - conentView.getMeasuredHeight() - hight);
        } else {
            this.setAnimationStyle(R.style.operation_popwindow_anim_style_down);
            arrow_up.setVisibility(View.VISIBLE);
            arrow_down.setVisibility(View.GONE);
            this.showAsDropDown(v, 0, 0);
        }
    }
}

怎麼用

建立實例並設定點擊回呼:

CustomOperationPopWindow customOperationPopWindow =
        new CustomOperationPopWindow(this, operationTypeSelectlist);
customOperationPopWindow.setOnItemMyListener(new CustomOperationPopWindow.OnItemListener() {
    @Override
    public void OnItemListener(int position, TypeSelect typeSelect) {
        // 這裡處理列表項被點擊後的業務邏輯
    }
});

在按鈕的點擊事件中彈出:

textView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 也可以額外傳入一個半透明背景 view,依業務需要顯示/隱藏
        customOperationPopWindow.showPopupWindow(textView);
    }
});

最終效果

以上就是主要程式碼。核心其實只有一個判斷:用 getLocationOnScreen 拿到按鈕的 Y 座標,跟螢幕高度的一半比大小,再決定呼叫 showAsDropDown 或 showAtLocation。剩下動畫與箭頭切換都是加分項。實作時有兩個小地方容易忽略:一是 conentView 必須先 measure 才能拿到 getMeasuredHeight(),否則朝上彈的位置會算錯;二是背景 ColorDrawable 一定要設定,不然 OnDismissListener 不會被觸發,背景也就無法復原。

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