image.png
前言
-
在Android開發(fā)中,Toast是最常見的提示方式了恐锣,但是在實際開發(fā)中,如果直接使用Toast還是相對比較復(fù)雜的:
Toast.makeText(context, R.string.text, Toast.LENGTH_SHORT).show();
寫這么長的代碼還是要花點時間的诀姚,那么接下來我們就要聊聊如何簡化鞭衩。
思路
-
說到簡化,第一個反應(yīng)當然是封裝成工具類了论衍,就像這樣:
public class ToastUtil { private ToastUtil(){} public static void showToast(@NonNull Context context, String text) { Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } }
這是最普遍的做法了,但是這樣做同樣也有問題炬丸,如果在我們需要彈Toast的地方,沒有Context對象呢焕阿?
這里我們就要看Toast所需要的這個上下文對象,Toast對這個對象沒有任何要求暮屡,也就是說毅桃,僅僅需要一個上下文對象而已,那么莺掠,我們是不是可以直接保存下一個一直存在的Context對象彻秆,所以的Toast都使用這一個對象。
實現(xiàn)
說到Android中一直存在的Context對象唇兑,大家會想到什么呢膀估?沒錯,就是Application帕棉。
-
下面是完整代碼:
public class ToastUtil{ private Context mContext; // 上下文對象 private ToastUtil(){} // 私有化構(gòu)造 private static final class Helper { // 內(nèi)部幫助類饼记,實現(xiàn)單例 static final ToastUtil INSTANCE = new ToastUtil(); } public static ToastUtil getInstance() { // 獲取單例對象 return Helper.INSTANCE; } public static void init(@NonNull Context context){ // 初始化Context Helper.INSTACE.mContext = context; } public void showToast(@StringRes int strResID) { // 根據(jù)資源id彈Toast if (mContext == null) { throw new RuntimeException("Please init the Context before showToast"); } showToast(mContext.getResources().getText(strResID)); } public void showToast(CharSequence str) { // 根據(jù)字符串彈Toast if (mContext == null) { throw new RuntimeException("Please init the Context before showToast"); } Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show(); } }
-
在Application中初始化
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); ToastUtil.init(this); } }
-
在任意類中使用:
ToastUtil.getInstance().showToast("彈Toast具则!");
總結(jié)
- 怎么樣,這樣封裝后是不是很方便低斋,如果你有其他的需求匪凡,也可以在工具類中添加方法。
- 也許有人會說啦病游,你把一個Context對象保存在靜態(tài)類中會不會造成內(nèi)存泄漏啊买猖?從技術(shù)角度說,這的確是內(nèi)存泄漏飞主,但是實際上我建議在Application中進行初始化高诺,因為Application也是一個Context對象,而這個對象是存在于應(yīng)用的整個生命周期的懒叛,所以并沒有任何影響薛窥。
- 當然啦眼姐,如果你非要在其他地方初始化ToastUtil,的確會造成內(nèi)存泄漏罢杉。