解决android7.0上某些PopuWindow显示位置不正确的问题

网上关于android系统7.0的popupwindow适配的解决方案,基本都是一样的,就是重写PopupWindow里面的方法

解决android7.0上某些PopuWindow显示位置不正确的问题

但是如何进行重写,对于一个初次接触的人来说,是个很头疼的问题。一来是涉及到java基础,二来是涉及到popupwindow的源码。

上个周我进行了几次尝试,始终达不到效果。最后仔细看了popup源码才明白。现在我给大家讲述一下过程。

1.popup底层源码的构造方法问题

    很多人直接进行自定义popupwindow类,但是一使用就会报错,popupwindw的构造方法报错    解决android7.0上某些PopuWindow显示位置不正确的问题

             查看源码发现,发现popup的构造方法有9个,

             解决android7.0上某些PopuWindow显示位置不正确的问题

 报错的构造方法是这个

  解决android7.0上某些PopuWindow显示位置不正确的问题             通过不停地查看最后我发现pop的构造方法之间是有联系的,也就是popup的

            

 * @param contentView the popup's content
 * @param width the popup's width
 * @param height the popup's height
 */
public PopupWindow(View contentView, int width, int height) {
    this(contentView, width, height, false);
}

说白了就是所有的构造方法最后用的几乎都是这个构造方法,也就是我们报错的这个构造方法。我们自定义popup时有两种,一种是有明确布局的自定义,一种是没有明确布局,但是无论是哪种,最后都是调用的是

       解决android7.0上某些PopuWindow显示位置不正确的问题

        因为我的自定义无需自定义布局(即在创建popup的时候没有明确的布局),所以我按照源码的方式必须重写不需要设定布局的构造方法,以及把方法的实现交给父类

 /**
  * 
  * 重写没有设定布局的构造方法
  * */
public ProductPopuWindow(View contentView, int width, int height) {
    /**
     *
     * 让父类实现,调用popup底层自己的构造方法
     * */
   super(contentView, width, height, false);
}
public ProductPopuWindow() {
    super(null, 0, 0);
}
public ProductPopuWindow(View contentView) {
    super(contentView, 0, 0);
}

public ProductPopuWindow(int width, int height) {
    super(null, width, height);
}

2.每次只是在点击第二次的时候,才会满足自己的效果,即第一次使用还是会遮蔽标题栏

  按照其他人的博客进行方法重写,重写的方法  

public void showAsDropDown(View anchor) 

   查看底层代码

/**
 * Display the content view in a popup window anchored to the bottom-left
 * corner of the anchor view. If there is not enough room on screen to show
 * the popup in its entirety, this method tries to find a parent scroll
 * view to scroll. If no parent scroll view can be scrolled, the
 * bottom-left corner of the popup is pinned at the top left corner of the
 * anchor view.
 *
 * @param anchor the view on which to pin the popup window
 *
 * @see #dismiss()
 */
public void showAsDropDown(View anchor) {
    showAsDropDown(anchor, 0, 0);
}

发现showAsDropDown(View anchor)的实现是调用public void showAsDropDown(View anchor, int xoff, int yoff)

所以我们还得继续重写这个方法

@Override
public void showAsDropDown(View anchorView, int xoff, int yoff) {
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
        int[] a = new int[2];
        anchorView.getLocationInWindow(a);
        showAtLocation(anchorView, Gravity.NO_GRAVITY, xoff, a[1] + anchorView.getHeight() + yoff);
    } else {
        super.showAsDropDown(anchorView, xoff, yoff);
    }
}

说道这里,其实看懂的人应该问一句,是不是可以直接重写后一个方法即可,答案是的