public class DatePickPopupWindow extends PopupWindow implements DatePicker.OnDateChangedListener { Activity mContext; DatePicker datePicker; public DatePickPopupWindow (Activity mContext, View parent) { this.mContext = mContext; final View view = View.inflate(mContext, R.layout.textview_popuwindow, null); datePicker = view.findViewById(R.id.datePicker); datePicker.init(2018, 06, 20, this); setWidth(ViewGroup.LayoutParams.MATCH_PARENT); setHeight(ViewGroup.LayoutParams.MATCH_PARENT); setFocusable(false); setOutsideTouchable(true); this.setBackgroundDrawable(new BitmapDrawable()); setBackgroundAlpha(0.5f); this.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { setBackgroundAlpha(1f);//菜单消失背景色还原 } }); setContentView(view); // showAsDropDown(parent,0,10);//某元素下方 // showAtLocation(parent, Gravit y.BOTTOM, 0, 0);//底部 showAtLocation(mContext.getWindow().getDecorView(), Gravity.CENTER, 0, 0); update(); view.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { int height = view.findViewById(R.id.pop_layout).getTop(); int y = (int) event.getY(); if (event.getAction() == MotionEvent.ACTION_UP) { if (y < height) { dismiss(); } } return true; } }); } /** * 设置添加屏幕的背景透明度 * * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明 */ public void setBackgroundAlpha(float bgAlpha) { WindowManager.LayoutParams lp = mContext.getWindow().getAttributes(); lp.alpha = bgAlpha; mContext.getWindow().setAttributes(lp); } @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // System.out.println("年=="+year+"月=="+monthOfYear+"日=="+dayOfMonth); Toast.makeText(mContext, "年==" + year + "月==" + monthOfYear + "日==" + dayOfMonth, Toast.LENGTH_SHORT).show(); dismiss(); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pop_layout" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <LinearLayout android:layout_width="wrap_content" android:orientation="vertical" android:gravity="center" android:background="#ffffff" android:layout_height="wrap_content"> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:visibility="visible" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>