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

Android PopupWindow 實戰:讓彈窗精準出現在指定控件下方

編輯:關於 Android 程式設計

PopupWindow 的定位一直是新手最容易翻车的地方。經過幾輪嘗試,我總結出一套能讓它穩定彈出在目標控件正下方的寫法,這裡把完整代碼和幾個容易踩雷的細節一起記錄下來。

一、封裝自訂的 PopupWindow

把 PopupWindow 繼承出來,在構造階段一次性處理佈局加載、寬高與焦點屬性,後續調用會乾淨很多。

package com.example.popwindowdemo;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;

public class TestPopwindow2 extends PopupWindow {

    // 根視圖
    private View mRootView;
    private LayoutInflater mInflater;

    public TestPopwindow2(Activity context) {
        super(context);
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRootView = mInflater.inflate(R.layout.test_popwindow_2, null);
        setContentView(mRootView);
        this.setWidth(LayoutParams.WRAP_CONTENT);
        this.setHeight(LayoutParams.WRAP_CONTENT);

        // 設置彈出相關屬性
        setTouchable(true);
        setOutsideTouchable(true);
        setFocusable(true);
        setBackgroundDrawable(new BitmapDrawable(context.getResources()));
        update();

        getContentView().setFocusableInTouchMode(true);
        getContentView().setFocusable(true);
        setAnimationStyle(R.style.AppBaseTheme);
    }
}

這裡有兩點值得注意。setBackgroundDrawable() 一定要呼叫,傳入一個空的 BitmapDrawable 即可——少了這一句,點擊外部消失的行為會失效。setFocusable(true) 則保證彈窗能正確接收返回鍵。

二、Activity 中的調用與定位

package com.example.popwindowdemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener, OnDismissListener {

    private TestPopwindow2 mTestPopwindow2 = null;

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

    private void InitUI() {
        mTestPopwindow2 = new TestPopwindow2(this);
        // 點擊其他位置時讓彈窗消失
        mTestPopwindow2.setOnDismissListener(this);

        Button buttonTest2 = (Button) findViewById(R.id.buttonTest2);
        buttonTest2.setOnClickListener(this);
    }

    private void OnPopwindowTest2() {
        if (mTestPopwindow2 == null) return;

        // 取得控件在屏幕上的位置
        int[] location = new int[2];
        View v = findViewById(R.id.buttonTest2);
        if (v != null) v.getLocationOnScreen(location);

        mTestPopwindow2.setAnimationStyle(R.style.AppBaseTheme);

        // 讓彈窗出現在按鈕下方
        mTestPopwindow2.showAtLocation(v, Gravity.TOP | Gravity.LEFT,
                location[0] - v.getWidth(), location[1] + v.getHeight());
    }

    // 彈窗內部控件的點擊事件
    public void OnclickTestListener(View view) {
        switch (view.getId()) {
            case R.id.layoutSeclect1:
                Toast.makeText(this, "系統熱門方案", Toast.LENGTH_SHORT).show();
                break;
            case R.id.layoutSeclect2:
                Toast.makeText(this, "個人熱門方案", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        if (mTestPopwindow2 != null) mTestPopwindow2.dismiss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonTest2:
                OnPopwindowTest2();
                break;
            default:
                break;
        }
    }

    @Override
    public void onDismiss() {
    }
}

定位的核心在 showAtLocation() 的四個參數:父容器、重力方向、x 偏移、y 偏移。這裡用 Gravity.TOP | Gravity.LEFT 搭配 location[0] - v.getWidth() 與 location[1] + v.getHeight(),就能讓彈窗左下角對齊按鈕正下方。

三、彈窗佈局

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:background="#0000"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <!-- 注意:popupwindow 的佈局不要使用 layout_marginTop 這類屬性,
         特別是在相對佈局中,整體靠左等設定都會影響定位 -->
    <LinearLayout android:id="@+id/hot_layout"
        android:background="@drawable/title_function_bg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout android:id="@+id/layoutSeclect1"
            android:clickable="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="OnclickTestListener">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="8dp"
                android:text="系統熱門方案"
                android:textColor="#fff"
                android:textSize="18sp" />
        </LinearLayout>

        <LinearLayout android:id="@+id/layoutSeclect2"
            android:clickable="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="OnclickTestListener">
            <TextView android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="8dp"
                android:text="個人熱門方案"
                android:textColor="#fff"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

這段註解裡提到的限制很關鍵:PopupWindow 的佈局盡量不要依賴 margin 之類的定位屬性。一旦佈局整體偏移,後續靠 showAtLocation 做的位置計算就會失準,這是絕大多數「彈窗位置不對」問題的根源。

四、主界面佈局

<LinearLayout android:id="@+id/LinearLayoutMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

    <LinearLayout android:gravity="right"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button android:id="@+id/buttonTest2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="測試2" />
    </LinearLayout>
</LinearLayout>

運行結果如下:

五、要點回顧

整理成三條 checklist:一是別忘了 setBackgroundDrawable(),否則外部點擊關閉失效;二是彈窗佈局本身保持乾淨,不要摻入定位類屬性;三是定位計算交給 getLocationOnScreen() 加 showAtLocation() 的偏移參數,不要試圖靠佈局 margin 硬湊。

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