Android中的PopupWindow详解

Android的对话框有两种:PopupWindow和AlertDialog。它们的不同点在于:

  • AlertDialog的位置固定,而PopupWindow的位置可以随意
  • AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的

PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下

  • showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
  • showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
  • showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移

 




复制代码
/** 
     * 初始化popWindow
     * */
    private void initPopWindow() {
        View popView = inflater.inflate(R.layout.listview_pop, null);
        popupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        //设置popwindow出现和消失动画
        popupWindow.setAnimationStyle(R.style.PopMenuAnimation);
        btn_pop_close = (ImageView) popView.findViewById(R.id.btn_pop_close);
        ll_pop_speech=(LinearLayout) popView.findViewById(R.id.ll_pop_speech);
        ll_pop_favor=(LinearLayout) popView.findViewById(R.id.ll_pop_favor);
        ll_pop_dislike=(LinearLayout) popView.findViewById(R.id.ll_pop_dislike);
        
        btn_pop_close.setOnClickListener(new popItemOnClickListener());
        ll_pop_speech.setOnClickListener(new popItemOnClickListener());
        ll_pop_favor.setOnClickListener(new popItemOnClickListener());
        ll_pop_dislike.setOnClickListener(new popItemOnClickListener());
    }
复制代码

 

 

 

复制代码
/** 
     * 显示popWindow
     * */
    public void showPop(View parent, int x, int y,int postion) {
        //设置popwindow显示位置
        popupWindow.showAtLocation(parent, 0, x, y);
        //获取popwindow焦点
        popupWindow.setFocusable(true);
        //设置popwindow如果点击外面区域,便关闭。
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
        if (popupWindow.isShowing()) {
            
        }
        
    }
复制代码
复制代码
/** 
     * 每个ITEM中more按钮对应的点击动作
     *
     **/
    public class popAction implements OnClickListener{
        int position;
        public popAction(int position){
            this.position = position;
        }
        @Override
        public void onClick(View v) {
            int[] arrayOfInt = new int[2];
            //获取点击按钮的坐标
            v.getLocationOnScreen(arrayOfInt);
            int x = arrayOfInt[0];
            int y = arrayOfInt[1];
            showPop(v, x , y, position);
        }
    }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值