Android 定时让popupwindow消失

        因为是在其他界面弹出的popupwindow,要在横屏切换回竖屏的时候,让popupwindow自动消失,因为弹出popupwindow是普通的类,没有监听横竖屏的函数,所以想到了使用定时器,定时3秒之后如果用户没有操作就让popupwindow消失,代码如下:

		// 创建弹出窗口
		popupMenu = new PopupWindow(view, sourceView.getWidth() * 2,
				LayoutParams.WRAP_CONTENT + 200);

		ColorDrawable cd = new ColorDrawable(R.color.white);
		popupMenu.setBackgroundDrawable(cd);
		popupMenu.update();
		popupMenu.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
		popupMenu.setTouchable(true); // 设置popupwindow可点击
		popupMenu.setOutsideTouchable(true); // 设置popupwindow外部可点击
		popupMenu.setFocusable(true); // 获取焦点
		ColorDrawable dw = new ColorDrawable(0x00);
		popupMenu.setBackgroundDrawable(dw);

		popupMenu.setTouchInterceptor(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					popupMenu.dismiss();
					return true;
				}
				timer.start();
				return false;
			}
		});

	}

	CountDownTimer timer = new CountDownTimer(3000, 10) {

		@Override
		public void onTick(long millisUntilFinished) {
		}

		@Override
		public void onFinish() {
			popupMenu.dismiss();

		}
	};

	@Override
	public PopupWindow createPupupWindow() {
		return popupMenu;
	}

	@Override
	public void showPopupMenu() {
		if (popupMenu != null && popupMenu.isShowing()) {
			popupMenu.dismiss();
		} else {
			popupMenu.showAsDropDown(sourceView, -sourceView.getWidth() / 2, 0);
			timer.start();
		}

	}
          关键点是使用CountDownTimer类,来进行定时,已经全部封装好了,不要去考虑子线程无法去改变UI界面的问题,还是非常好用的。

你可能感兴趣的:(Android)