您的位置:首页 > 移动开发 > Android开发

Android 弹出窗口 定时关闭

2013-04-07 19:49 351 查看
工作中正需要一个弹出窗口的定时关闭,考虑了下可以使用Handler,Timer或者AsyncTask基础结合实现。不过,偶然发现了原来Android的api竟然已有类似功能的实现类CountDownTimer。该类实现了在指定时间间隔进行倒计时功能。

查看Android的SDK,看到该类

public abstract class

CountDownTimer

extends Object

java.lang.Object
android.os.CountDownTimer
是一个抽象类。运行在应用的子线程。主要的方法:


public abstractvoid onFinish() {
}
public abstract void onTick(long
millisUntilFinished)
尽管CountDownTimer类是运行在应用的子线程,但上面实现的两个方法却是运行在主线程的。效果图:



下面上代码:

public class CountDownDialog 
{
	private Activity _activity;
	private LayoutInflater _inflater;
	private View _layout;
	private View _anchor;
	private TextView tv_tips;
	
	private PopupWindow _popupWindow;
	private CountTimer countTimer;
	
	/**
	 * 构造函数
	 * @param activity上下文对象
	 * @param anchor 锚点
	 * @param millisInFuture 倒计的时间数,以毫秒为单位
	 * @param countDownInterval 倒计每秒中间的间隔时间,以毫秒为单位
	 */
	public CountDownDialog(Activity activity,View anchor,long millisInFuture, long countDownInterval)
	{
		_activity = activity;
		_anchor = anchor;
		_inflater = (LayoutInflater) _activity.getSystemService("layout_inflater");
		_layout = (LinearLayout) _inflater.inflate(R.layout.count_dialog, null, true);
		tv_tips = (TextView)_layout.findViewById(R.id.tv_countdialog_tips);
		countTimer = new CountTimer(millisInFuture,countDownInterval);
	}
	
	public void show()
	{
		if(_popupWindow == null)
		{
			_popupWindow = new PopupWindow(_layout,250, 200,true);
		}
		_popupWindow.showAtLocation(_anchor, Gravity.CENTER, 0, 0);
		_popupWindow.update();
		countTimer.start();
	}
	
	public void cancle()
	{
		if(_popupWindow != null && _popupWindow.isShowing())
		{
			countTimer.cancel();
			_popupWindow.dismiss();
			if(_activity != null)
			{
				_activity.finish();
			}
		}
	}
	
	class CountTimer extends CountDownTimer 
	{

		/**
		 * 构造函数
		 * @param millisInFuture 倒计的时间数,以毫秒为单位
		 * @param countDownInterval 倒计每秒中间的间隔时间,以毫秒为单位
		 */
		public CountTimer(long millisInFuture, long countDownInterval)
		{
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish()
		{
			cancle();
		}

		@Override
		public void onTick(long millisUntilFinished)
		{
			tv_tips.setText(_activity.getString(R.string.issaving)+millisUntilFinished / 1000 + _activity.getString(R.string.second));
		}
		
	}
	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: