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

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

clipboard.png
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);//设置动画
     
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值