1. 简介
刚开始用Toast的时候,经常记不住使用方法。当记得住使用方法的时候,有不喜欢其传统的啰嗦用法。所以,就根据周边看到的一些情况,梳理出本文的偷懒用法。
2. 方法一:静态方法,无须构造对象实例
代码如下:
package com.example.utils;
import android.content.Context;
import android.widget.Toast;
public class ToastUtils {
public static void showShort(Context context, String msg) {
show(context, msg, Toast.LENGTH_SHORT);
}
public static void showLong(Context context, String msg) {
show(context, msg, Toast.LENGTH_LONG);
}
private static void show(Context context, String msg, int duration) {
Toast.makeText(context, msg, duration).show();
}
}
3. 方法二:需构造对象示例,但后续使用更加方便
package com.example.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;
@SuppressLint("ShowToast")
public class ToastHelper {
private Toast toast;
public ToastHelper(Context context) {
if (context == null) {
throw new NullPointerException("Context can not be null!");
}
toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
}
public void show(String msg) {
toast.setText(msg);
toast.show();
}
public void show(int resourceId) {
toast.setText(resourceId);
toast.show();
}
}
4. 比较
第一种方法适用于调用不频繁的情况,但每次调用要传入Context等参数;第二种适合较大的类中调用,只需要在构造函数中创建一次ToastHelper实例,作为数据成员,后续直接调用show(),加上一个入参即可。