Android中的PopupWindows详解
PopupWindows是类似与dialog的弹出窗口,不过比dialog更加方便的显示view的位置。
PopupWindows的用法分为以下几步:
1. 定义MyPopupWindows继承PopupWindows.
2. 重写PopupWindows的构造方法。
3. 实现自己的showPopupWindows()方法用来控制PopupWindows的显示和消失。
下面通过一个实例来看看:
public class MyPopwindows extends PopupWindow {
private View conentView;
private int h,w;
private TextView costReport,costDetail;
private Context mcontext;
public MyPopwindows(final Activity context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mcontext=context;
conentView = inflater.inflate(R.layout.mypop, null);
costDetail=(TextView)conentView.findViewById(R.id.costDetail);
costReport=(TextView)conentView.findViewById(R.id.costReport);
w = context.getWindowManager().getDefaultDisplay().getWidth();
// h = context.getWindowManager().getDefaultDisplay().getHeight();
h=getmyHeidth();
// 设置SelectPicPopupWindow的View
this.setContentView(conentView);
// 设置SelectPicPopupWindow弹出窗体的宽
this.setWidth(w / 4);
// 设置SelectPicPopupWindow弹出窗体的高
this.setHeight(GridLayout.LayoutParams.WRAP_CONTENT);
// 设置SelectPicPopupWindow弹出窗体可点击
this.setBackgroundDrawable(new BitmapDrawable());
this.setOutsideTouchable(true);
}
public void showPopupWindow(View parent) {
int[] location = new int[2];
parent.getLocationOnScreen(location);
if(this.isShowing())
{
this.dismiss();
}
else
{
this.showAtLocation(parent, Gravity.BOTTOM,(location[0] + parent.getWidth() / 2) - w/ 2, h+ Constant.height);
}
}
private int getmyHeidth()
{
Bitmap bitmap = BitmapFactory.decodeResource(mcontext.getResources(), R.drawable.t_kaoqinguanli_p);
int height = bitmap.getHeight();
return height;
}
}
上面的mypop是自定义的view也就是触发showPopupWindow()时显示的图片。在自己的程序中只要定义一个MyPopupWindows 然后调用showPopupWindow()方法就可以。this.showAtLocation(parent, Gravity.BOTTOM,(location[0] + parent.getWidth() / 2) - w/ 2, h+ Constant.height);设置弹出窗口的位置。