android 中PopupWindow的使用

本文介绍了一种在Android应用中使用PopupWindow的方法,并解决了当PopupWindow显示在同一父View上导致的错误问题。通过代码示例展示了如何实现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);

}

转载于:https://www.cnblogs.com/xxzjyf/p/5897241.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值