Android PopupWindow详解

Android 开发中会有悬浮窗(飘窗)的需求,其实就是利用PopupWindow的api来实现,下面就讲解下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);
        }
    }
发布了262 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/baidu_41666295/article/details/105028862