android PopupWindow有个方法showAtLocation,可以指定PopupWindow显示的位置,以前都是在控制之下显示,可以用showAsDropDown,这个比较简单,就不说了,现在想要在控件之上显示,纠结了半天,刚开始设置PopupWindow的Width和Height用到的是LayoutParams.WRAP_CONTENT,结果死活也不到控件上面显示,没办法,最后设定了一个固定的Width和Height就成功了,下面上代码,已经写了部分注释
public void showPopuptWindow(View v,String text_where,String text_err,Bitmap bitmap) {
View view=LayoutInflater.from(this).inflate(R.layout.popupwindow_layout, null);
//此处 width,height一定要写具体值,若用wrap_content,则不会出现在控件之上
popupWindow=new PopupWindow(view, 437, 447);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
int [] position = new int[2];
//此方法获取控件在屏幕的位置
v.getLocationOnScreen(position);
System.out.println(position[0]+">>>"+position[1]);
err_text=(TextView)view.findViewById(R.id.err_text);
err_where=(TextView)view.findViewById(R.id.err_where);
err_image=(ImageView)view.findViewById(R.id.err_img);
err_text.setText(text_err);
err_where.setText(text_where);
err_image.setImageBitmap(bitmap);
//此处position[0]-popupWindow.getWidth()/2+18可以根据实际调整
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, position[0]-popupWindow.getWidth()/2+18,position[1]-popupWindow.getHeight());
}