長期表示を実現するtoast

1870 ワード

public class CustomToast{

	private Handler handler;
	public Toast toast;
	private int LONG_SHOW=-1;
	private boolean isShowing=false;
	
	public CustomToast(Context context) {
		this(context,null);
	}
	
	public CustomToast(Context context,Toast toast){
		if(null==toast) 
			this.toast=new Toast(context);
		else 
			this.toast=toast;
		handler = new Handler();
	}
	
	public void show(){
		Log.i("show","<<<<<<<<<<>>>>>>>>>>>>>>");
		isShowing=true;
		if(toast.getDuration()==LONG_SHOW){
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
			showUntilHide();
		}else{
			toast.show();
		}
	}
	
	public void hide(){
		Log.i("hide","<<<<<<<<<<>>>>>>>>>>>>>>");
		if(null!=toast){
			toast.cancel();
		}
			
		isShowing=false;
	}
	
	public boolean isShow(){
		return isShowing;
	}
	
	private void showUntilHide(){
		Log.i("showUntileHide","<<<<<<<<<<>>>>>>>>>>>>>>");
		if(null==toast) return;
		if(isShowing){
			toast.show();
			handler.postDelayed(r, 3000);
		}
	}
	
	Runnable r = new Runnable(){
		public void run(){
			showUntilHide();
		}
	};

}

 
呼び出し方法:
 
Toast toast = new Toast(TestAndroid.this);

toast.setDuration(-1);
	
CustomToast ct = new CustomToast(this,toast);

ct.show();