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

Android PopupWindow 學習總結:用法與三個實戰坑點

編輯:關於 Android 程式設計

PopupWindow 可以浮現在畫面任意位置,比 Dialog 更靈活。不過實際使用時有幾處細節容易踩坑,本文整理出來。

一、三種顯示方式

  • showAsDropDown(View anchor):相對於指定控件的正左下方顯示,無偏移。
  • showAsDropDown(View anchor, int xoff, int yoff):相對於指定控件顯示,可自訂偏移量。
  • showAtLocation(View parent, int gravity, int x, int y):相對於父容器並搭配 Gravity 定位(如 Gravity.CENTER、Gravity.BOTTOM),可自訂偏移。

二、兩種建立方式

第一種,直接在建構子中帶入 view 與寬高:

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 載入視窗佈局檔
View view = inflater.inflate(R.layout.pop_view, null);

/*** 建立模式一 ***/
pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// 點擊視窗外側時視窗消失
pop.setOutsideTouchable(true);
// 必須設定此參數才能接收點擊
pop.setFocusable(true);

第二種,先用無參數建構子,再逐步設定內容與尺寸:

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.pop_view, null);

/*** 建立模式二 ***/
pop = new PopupWindow(this);
pop.setContentView(view);
pop.setWidth(LayoutParams.WRAP_CONTENT);
pop.setHeight(LayoutParams.WRAP_CONTENT);
pop.setOutsideTouchable(true);
pop.setFocusable(true);

三、坑點一:兩種模式的行為差異

如果不加上這行:

pop.setBackgroundDrawable(new BitmapDrawable());

兩種模式的差異就會顯現出來:模式一會出現「點擊其他區域視窗不消失」的問題;模式二則會多出一圈灰色邊框。

這行程式碼的作用是為 PopupWindow 設定背景。模式二預設會套上一個灰色背景框,想去掉就得靠它。

四、坑點二:為什麼不能寫 setBackgroundDrawable(null)

直覺上,既然目的是「不要背景」,傳 null 不就完了?實測在模式二下使用 setBackgroundDrawable(null),會導致「點擊外部區域視窗不消失」的問題重新出現。這裡目前只能知其然:社群中普遍給出的解法就是改用 new BitmapDrawable(),至於底層為何如此,暫未找到權威解釋。

五、坑點三:getWidth() 拿到 -2

若建立時用 LayoutParams.WRAP_CONTENT 設定寬高,事後呼叫:

System.out.println("pop寬度=" + pop.getWidth());
System.out.println("pop高度=" + pop.getHeight());

印出來的會是 -2,也就是 LayoutParams.WRAP_CONTENT 的常數值,而非視窗實際渲染後的長寬。也就是說,PopupWindow 是「你給什麼就回什麼」,不會替你做最終量測。

解法是先手動量測內容 view,再把結果設回去:

// 想取得 PopupWindow 實際的佈局大小,可以這樣做
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int viewWidth = view.getMeasuredWidth();
int viewHeight = view.getMeasuredHeight();
pop.setWidth(viewWidth);
pop.setHeight(viewHeight);

六、完整測試程式碼

佈局檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="dianji" />
</LinearLayout>

Activity:

package com.example.popupwindowdemo;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow;

public class MainActivity extends Activity {

    private PopupWindow pop;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LayoutInflater inflater = (LayoutInflater) this.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        // 載入視窗佈局檔
        View view = inflater.inflate(R.layout.pop_view, null);

        /*** 建立模式二 ***/
        pop = new PopupWindow(this);
        pop.setContentView(view);

        // 若寬高設為 WRAP_CONTENT,getWidth() 會回傳 -2
        // pop.setWidth(LayoutParams.WRAP_CONTENT);
        // pop.setHeight(LayoutParams.WRAP_CONTENT);

        // 先量測再設定,才能取得實際尺寸
        view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        int viewWidth = view.getMeasuredWidth();
        int viewHeight = view.getMeasuredHeight();
        pop.setWidth(viewWidth);
        pop.setHeight(viewHeight);
        System.out.println("pop寬度=" + pop.getWidth());
        System.out.println("pop高度=" + pop.getHeight());

        // 必須設定,否則模式一會無法點擊外部消失,模式二會出現灰色邊框
        pop.setBackgroundDrawable(new BitmapDrawable());
        // pop.setBackgroundDrawable(null);

        pop.setOutsideTouchable(true);
        pop.setFocusable(true);

        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pop.isShowing()) {
                    pop.dismiss();
                } else {
                    pop.showAsDropDown(v);
                }
            }
        });
    }
}

這些問題單看都不大,但真正遇到時往往要耗不少時間排查,因此記錄下來與各位共勉。

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