Android开发-弹框-PopupWindow弹框

627 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

前面已经介绍了弹框的三种实现方式了,其中系统的Dialog和系统的Window都是比较简单,应用场景也是比较局限,AlterDialog的使用方式以及应用场景都是相对来说多点,它们都是弹框UI展示的原始方式,也是基础实现,正常的实现都可以使用他们来开发完成业务需求,下面我们介绍另一种实现方式,PopupWindow,它的设计初衷不是为了弹框,而是悬浮框,但是也可以通过代码实现展示成弹框的样式,这里拿出来说是因为在实际开发过程中用到的比较多,应用场景也比较频繁。下面就介绍下它的简单实现方法。

PopupWindow的定义以及实现

为什么把PopupWindow作为弹框来介绍,因为它相对于弹框,它的显示位置更加灵活,可以很方便的指定要显示的位置;官方的定义:A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity. 翻译出来是什么意思呢,一个悬浮框,被用来展示任意的View,这个弹框是一个悬浮框,展现在当前Activity的最顶部。

PopupWindow常用构造方法

1)public PopupWindow (Context context)
2)public PopupWindow (View contentView)
3)public PopupWindow (View contentView, int width, int height)

以上3个构造方法是PopupWindow比较常用的,第一个是最常用的,2、3相对来说用的不是特别多。

PopupWindow常用属性方法

  • setContentView:设置PopupWindow显示的View;
  • showAsDropDown(View anchor) :设置显示在某个View的下面;
  • showAsDropDown(View anchor, int xoff, int yoff) :和上面的方法类似,只是多了2个参数,水平和竖直方向的偏移量;
  • showAtLocation(View parent, int gravity, int x, int y) : 设置相对于父布局的位置,第二个参数是设置在父布局的相对位置,Grivaty;第三个参数也是偏移量,可以设置偏移或无偏移;
  • setWidth/setHeight:设置宽高;
  • setAnimationStyle(int): 设置弹出的动画效果;

PopupWindow的使用

public class MainActivity extends Activity {

 
    private PopupWindow popWindow

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        popWindow = new PopupWindow(this);
        btn_popup.setOnClickListener{ v->
          initPopWindow(v); 
        }
    }

    private void initPopWindow(View parentView){
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_popup, null, false);
        popWindow.setContentView(view);
        popWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));//需要设置一个背景色
        //设置水平偏移量100,在父布局下面
        popWindow.showAsDropDown(parentView, 100, 0);
    }
}

就简单的设置了几个属性值, 就可以实现一个再btn下面显示的PopupWindow了,作为特殊弹框的PopupWindow,实现起来是不是也很简单,而且更加灵活,更加方便,但是有个注意点就是系统版本的兼容性问题,项目中遇到过在设置显示在某个布局下面不生效的问题,具体可以参考以下方法:

/**
 * 解决popupwindow 弹出显示问题,现在某个布局下面不生效,以及是否开启刘海和底部菜单栏适配
 */
fun showAsDropDown(pw: PopupWindow, anchor: View, xoff: Int, yoff: Int) {
    if (Build.VERSION.SDK_INT >= 24) {
        val visibleFrame = Rect()
        anchor.getWindowVisibleDisplayFrame(visibleFrame)
        val height = anchor.resources.displayMetrics.heightPixels - visibleFrame.bottom
        if (height != 0) {
            pw.height = height
        } else {
            pw.height = anchor.resources.displayMetrics.heightPixels - anchor.bottom
        }
        pw.showAsDropDown(anchor, xoff, yoff)
    } else {
        pw.showAsDropDown(anchor, xoff, yoff)
    }
}