Android 之路 (6) - 關於Toast和Log的封裝
引言
上篇完成了對Dialog的簡單封裝,本篇將對Android開發中另外兩個常用工具類的封裝:T(Toast)和L(Log)。
正文
Toast的簡單封裝
這一步主要是將建立 Toast 的佈局抽取出來,形成一個單獨的工具類,呼叫的時候直接通過T.showToast進行呼叫即可,程式碼如下:
/** * 描述:Toast工具類. */ public class T { /** * 描述:Toast提示文字. * * @param textStr 文字 */ public static void showToast(Context context, String textStr) { Toast.makeText(context.getApplicationContext(), textStr, Toast.LENGTH_SHORT).show(); } /** * 描述:Toast提示文字. * * @param resId 文字的資源ID */ public static void showToast(Context context, int resId) { Context mContext = context.getApplicationContext(); showToast(mContext, mContext.getResources().getString(resId)); } }
這裡需要注意的是,我們在 makeText
傳入的 context
一定要使用 ApplicationContext
,以免造成 記憶體洩漏
。
執行起來看看效果吧:

Toast
Toast的自定義佈局
前面使用的系統預設 Toast 樣式,看上去並不怎麼好看,所以我們需要進行自定義,進行美化。而Toast為我們提供了一個 setView
的方法,我們可以自行建立xml佈局進行自定義實現,接下來就是進入自定義Toast佈局的時間。
建立Toast背景
實現一個半透明的shap作為Toast的背景。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:radius="4dp" /> <solid android:color="#88000000" /> </shape>
建立Toast佈局
xml主要就是放了一個TextView,然後設定TextView的背景、字號、顏色等。
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toast_background" android:gravity="center" android:orientation="vertical" android:paddingBottom="12dp" android:paddingLeft="30dp" android:paddingRight="30dp" android:id="@+id/tv_msg" android:text="Toast" android:textColor="#fff" android:textSize="12sp" android:paddingTop="12dp"/>
建立Toast
這裡需要注意的是:在showToast時候的引數Context是不定的,所以我們只能通過 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
方式來獲取佈局解析器。
具體程式碼如下:
/** * 描述:Toast提示文字. * * @param text 文字 */ public static void showToast(Context context, String text) { // 獲取佈局解析器 LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (!TextUtils.isEmpty(text) && null != inflate) { // 解析佈局 View layout = inflate.inflate(R.layout.layout_toast, null); TextView tvMsg = (TextView) layout.findViewById((R.id.tv_msg)); tvMsg.setText(text); Toast toast = new Toast(context.getApplicationContext()); // 底部距離150 toast.setGravity(Gravity.BOTTOM, 0, 150); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } } /** * 描述:Toast提示文字. * * @param resId 文字的資源ID */ public static void showToast(Context context, int resId) { Context mContext = context.getApplicationContext(); showToast(mContext, mContext.getResources().getString(resId)); }
自定義Toast效果
完成程式碼編寫,來看看效果吧:

自定義Toast
看上去的確是要比系統的樣式好看多了,那麼Toast就暫時到這裡。
Log
Log的選型
關於log,個人不建議對系統的log直接進行封裝,系統的log有以下缺陷性:
無法定位log輸出行(列印log的位置)
無法定義log的輸出格式,如Json和xml
對於list、map等的輸出不友好
不支援將log保持在檔案中
針對以上缺陷,我推薦使用 ofollow,noindex">logger 來進行基礎封裝,使用方法也比較簡單。
Log的封裝
依賴logger
api 'com.orhanobut:logger:2.2.0'
沒有條件的同學記得使用阿里的中央倉庫:
repositories { maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } }
T工具類也沒有什麼大的內容,只寫了簡單的幾個常用方法,其它請自行斟酌、按需編碼,就直接看程式碼吧:
/** * Logcat工具類 */ public class L { private L() { throw new UnsupportedOperationException("cannot be instantiated"); } /** * 是否需要列印bug,可以在application的onCreate函式裡面初始化 */ public static boolean isDebug = true; // 下面四個是預設tag的函式 public static void i(String msg) { if (isDebug) Logger.i(msg); } public static void d(String msg) { if (isDebug) Logger.d(msg); } public static void e(String msg) { if (isDebug) Logger.e(msg); } public static void v(String msg) { if (isDebug) Logger.v(msg); } // 下面是傳入自定義tag的函式 public static void i(String tag, String msg) { if (isDebug) Logger.e(msg); } public static void d(String tag, String msg) { if (isDebug) Logger.e(msg); } public static void e(String tag, String msg) { if (isDebug) Logger.e(msg); } public static void v(String tag, String msg) { if (isDebug) Logger.e(msg); } }
L演示
十分不想寫這部分演示,果然還是踩到坑了:2.0版本增加了Adapter,必須要進行初始化 Logger.addLogAdapter(new AndroidLogAdapter());
才可以正常列印。
例子內容:
public void jsonLog(View view) { LoginDto.UserInfo userInfo = new LoginDto.UserInfo(); userInfo.setAge(25); userInfo.setEmail("[email protected]"); userInfo.setNickName("aohanyao"); userInfo.setUserName("aohanyao"); // 序列化成json L.json(new Gson().toJson(userInfo)); } public void listLog(View view) { List<String> list = new ArrayList<>(); list.add("jsonLog"); list.add("mapLog"); list.add("ordinaryLog"); L.list(list); } public void ordinaryLog(View view) { L.e("ordinaryLog"); }
執行結果:

LogExample
最後
總結
完成了兩個常用工具類的封裝:T(Toast)和L(Log)
順便更改了Example的結構頁面