Android中使PopupWindow显示在指定控件的上下左右!

647 查看

**1.View中的方法getLocationOnScreen(int[] location):获取该控件在屏幕中的绝对坐标并将坐标保存在数组中:如下图所示,A为屏幕的原点,R,C点即为view的绝对坐标的位置
getLocationInWindow(int[] location) :获取控件相对于父窗口的坐标,如c在R中,获取c在R中的坐标**


2.

public void click1(View v) {
       
        View view = View.inflate(this, R.layout.dialog, null);
        //获取PopupWindow中View的宽高
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();
        PopupWindow popupWindow = new PopupWindow(view, getResources().getDisplayMetrics().widthPixels
                , getResources().getDisplayMetrics().heightPixels);
        popupWindow.setFocusable(true);//popupwindow设置焦点

        popupWindow.setBackgroundDrawable(new ColorDrawable(0xaa000000));//设置背景
        popupWindow.setOutsideTouchable(true);//点击外面窗口消失
        // popupWindow.showAsDropDown(v,0,0);
        //获取点击View的坐标
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        popupWindow.showAsDropDown(v);//在v的下面
        //显示在上方
        popupWindow.showAtLocation(v,Gravity.NO_GRAVITY,location[0]+v.getWidth()/2,location[1]-measuredHeight);
       //显示在正上方
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - measuredWidth / 2, location[1]-measuredHeight);
           //显示在左方
        popupWindow.showAtLocation(v,Gravity.NO_GRAVITY,location[0]-popupWindow.getWidth(),location[1]);
        //显示在下方
        popupWindow.showAtLocation(v,Gravity.NO_GRAVITY,location[0]+v.getWidth(),location[1]);
       popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);//设置动画
     
    }