android 中PopupWindow的使用
这个popupwindow也是在某一个作者那看到了,但是很久了,忘记是哪位了,只是今天又用到,而且遇到些问题,所以就贴出来共享下,也把问题提出来以便其他读者犯错。
定义两个View
private View parent;
private View layout;
//此方法写在activity中
private void showPopu(){
parent = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
layout = View.inflate(mContext, R.layout.popuwindow_calendar, null);
myCalendarView = (MyCalendarView) layout.findViewById(R.id.calendarView);
myCalendarView.setOnItemClickListener(new CalendarItemClickListener());
//下面这个判断是用于在未清除layout时,显示在同一个父View上,导致报错,我就是遇到这个问题的
if(layout != null && layout.getParent() != null){
((ViewGroup) layout.getParent()).removeAllViews();
}
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
calendarPopWindow = new PopupWindow(layout, width, height);
calendarPopWindow.setAnimationStyle(R.style.AnimBottom);
calendarPopWindow.setFocusable(true);
// 控制popuWindow点击屏幕其他地方消失
calendarPopWindow.setOutsideTouchable(true); // 触摸popuWindow外部,popuWindow消失,要求popuWindow必须有背景图
calendarPopWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
}
});
layout.findViewById(R.id.id_last_month).setOnClickListener(this);
layout.findViewById(R.id.id_next_month).setOnClickListener(this);
tvMonth = (TextView) layout.findViewById(R.id.id_year_month);
tvMonth.setText(myCalendarView.getYearAndmonth());
// calendarPopWindow.showAsDropDown(ivDate, 0, 50);
ColorDrawable dw = new ColorDrawable(0x80000000); // 设置popuwindow背景
calendarPopWindow.setBackgroundDrawable(dw);
calendarPopWindow.showAtLocation(parent, Gravity.BOTTOM
| Gravity.CENTER_HORIZONTAL, 0, 0);
}