Contents
  1. 1. 2015-09-22 09:11:57
    1. 1.1. PopupWindow 基本用法(View加载、计算宽度、参考显示)
  2. 2. 2015/11/5 9:01:49
    1. 2.0.1. BadToken错误,popWindow的getWidth是0、-2

2015-09-22 09:11:57

  1. 用一个View加载要显示的布局。
  2. 创建PopupWindow对象,传入上述view以及宽高作为参数。(PopupWindow(View contentView, int width, int height))
  3. 设置PopupWindow的背景。(setBackgroundDrawable)
  4. 设置PopupWindow的显示位置,并且将其显示。(两种方法)
  5. popupWindow.setFocusable(true);
  6. popupWindow.setOutsideTouchable(true); // 设置允许在外点击消失
  • (showAsDropDown) 相对某个view的位置

    public void showAsDropDown(View anchor)
    
    public void showAsDropDown(View anchor, int xoff, int yoff)
    
    public void showAsDropDown(View anchor, int xoff, int yoff, int gravity)
    
  • (showAsLocation)相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移

    public void showAtLocation(View parent, int gravity, int x, int y)
    
    public void showAtLocation(IBinder token, int gravity, int x, int y)
    

下述是示例代码:

View view = View.inflate(this,R.layout.Erintrus,null);

PopupWindow pop = new PopupWindow(view,300,300, true); //设置宽高
//如果设置为自适应LinearLayout.LayoutParams.WRAP_CONTENT,则其宽高为背景图片的宽高

pop.setBackgroundDrawable(context.getResource().getDrawable(R.drawable.test));//必须设置,否则点击不能取消,并且卡死屏幕

int width = context.getResources().getDisplayMetrics().widthPixels;//获取屏幕宽

int menuWidth = pop.getWidth();//获取popupWindow的宽度,由于上述设置了300px,所以这的值是300

int menuShowXoff = (width-menuWidth)/2; //设置其显示位置的横坐标

pop.showAsDropDown(actionBar, menuShowXoff, 0); //以actionbar为参考,的位置。

pw.showAtLocation(actionBar, Gravity.CENTER_HORIZONTAL|Gravity.TOP, 0, 50);

2015/11/5 9:01:49

BadToken错误,popWindow的getWidth是0、-2

  • Bad Token showAsDropDown、showAtLocation方法不能放在OnCreate

解决办法: 放在点击事件里

  • popWindow的getWidth是0、-2的原因是设置了宽高设置了Warp_content

    PopupWindow pop = new PopupWindow(view,LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT, true); //设置宽高
    

解决办法:添加如下代码

popupView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popWidth = popupWindow.getContentView().getMeasuredWidth();//获取宽度
Contents
  1. 1. 2015-09-22 09:11:57
    1. 1.1. PopupWindow 基本用法(View加载、计算宽度、参考显示)
  2. 2. 2015/11/5 9:01:49
    1. 2.0.1. BadToken错误,popWindow的getWidth是0、-2