Android進階篇-Toast自定義顯示時間

public class CustomToast { 
	public static final int LENGTH_MAX = -1; 
	private boolean mCanceled = true;
	private Handler mHandler; 
	private Context mContext; 
	private Toast mToast; 

	public CustomToast(Context context) { 
		this(context,new Handler()); 
	} 


	public CustomToast(Context context,Handler h) { 
		mContext = context; 
		mHandler = h; 
		mToast = Toast.makeText(mContext,"",Toast.LENGTH_SHORT); 
		mToast.setGravity(Gravity.BOTTOM, 0, 0); 
	} 

	public void show(int resId,int duration) { 
		mToast.setText(resId); 
		if(duration != LENGTH_MAX) { 
			mToast.setDuration(duration); 
			mToast.show(); 
		 } else if(mCanceled) { 
			 mToast.setDuration(Toast.LENGTH_LONG);
			 mCanceled = false;
			 showUntilCancel(); 
		 } 
	}
	
	/**
	 * @param text 要顯示的內容
	 * @param duration 顯示的時間長
	 * 根據LENGTH_MAX進行判斷
	 * 如果不匹配,進行系統顯示
	 * 如果匹配,永久顯示,直到調用hide()
	 */
	public void show(String text,int duration) { 
		mToast.setText(text); 
		if(duration != LENGTH_MAX) { 
			mToast.setDuration(duration); 
			mToast.show(); 
			} else { 
				if(mCanceled) { 
					mToast.setDuration(Toast.LENGTH_LONG); 
					mCanceled = false; 
					showUntilCancel();
				}
			} 
		} 

	/**
	 * 隱藏Toast
	 */
	public void hide(){
		mToast.cancel();
		mCanceled = true;
	}
	
	public boolean isShowing() {
		return !mCanceled;
	}
	
	private void showUntilCancel() { 
		if(mCanceled) 
			return; 
		mToast.show();
		mHandler.postDelayed(new Runnable() {
			public void run() { 
				showUntilCancel(); 
			}
		},3000); 
	} 
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章