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保持在文件中

针对以上缺陷,我推荐使用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("aohanyao@gmail.com");
        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的结构页面

源码-tag-v0.06

微信公众号

来都来了,就给个关注吧,时不时会悄悄的推送一些小技巧的文章~~
AndroidRookie

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值