0%

Android开发 PopupWindow显示在指定控件上方方法

PopupWindow没有显示在指定控件上方的方法,只好自己定义类继承PopupWindow来实现。有一点需要注意的是,在Android中,所有的View都必须在显示以后才获取到正确的高度和宽度,而PopupWindow定位使用的是设置PopupWindow的左上角座标,所以,我们在获取到指定控件在屏幕中的座标后,需要加上PopupWindow的高度,所以,这个方法有一定的限制,PopupWindow的高度必须是确定的,或者说,必须先计算出即将显示出来的PopupWindow的高度。

package com.pocketdigi.views;

import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;
import cn.jtang.discussion.R;

public class CustomPopupWindow extends PopupWindow {
    public CustomPopupWindow(View contentView, int width, int height) {
        super(contentView, width, height, false);
    }
    /**
     * 在指定控件上方显示,默认x座标与指定控件的中点x座标相同
     * @param anchor
     * @param xoff
     * @param yoff
     */
    public void showAsPullUp(View anchor, int xoff, int yoff)
    {
        //保存anchor在屏幕中的位置
        int[] location=new int[2];
        //保存anchor上部中点
        int[] anchorCenter=new int[2];
        //读取位置anchor座标
        anchor.getLocationOnScreen(location);
        //计算anchor中点
        anchorCenter[0]=location[0]+anchor.getWidth()/2;
        anchorCenter[1]=location[1];
        super.showAtLocation(anchor, Gravity.TOP|Gravity.LEFT, anchorCenter[0]+xoff, anchorCenter[1]-anchor.getContext().getResources().getDimensionPixelSize(R.dimen.popup_upload_height)+yoff);
    }
}