Android—App—必备开发组件—通用组件篇—ToastUtil

一、First and Foremost :

1.1、简述:

  • 作为Android系统提供的基类,Toast是最简单的提示消息类,特点悬浮,跨界面(Activity)特定时间内自动销毁。

1.2、简单使用:

Toast.makeText(getApplicationContext(), "你想提示的信息",Toast.LENGTH_SHORT).show();

1.3、深入分析:

  • 查看源码会发现makeText方法会返回一个Toast实例,如下:
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {  
      Toast result = new Toast(context);  

      LayoutInflater inflate = (LayoutInflater)  
              context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
      View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);  
      TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);  
      tv.setText(text);  
        
      result.mNextView = v;  
      result.mDuration = duration;  
  
      return result;  
  }  
  • 由于每次都会new一个新的Toast,这也就是为什么如果同时间多次调用makeText会弹出多个提示框,直到所有的提示完成才消失

1.4、实际项目中如何使用:

  • 我们看到上述源码,用到了layout组件,那也就是说我们也可以定义自己的View,Toast提供了在屏幕上的显示位置。这样我们就可以自定义样式并且在需要的位置显示Toast。

二、No picture,You say a JB:

本例中使用的是在界面顶部弹出自定义的Toast,如果成功弹出绿色提示条,失败弹出黄色提示条


Android—App—必备开发组件—通用组件篇—ToastUtil_第1张图片
极路由APP顶部提示效果【网络不通】

三、Show Me Code:

3.1、Toast-工具类

package com.ray.utils;

import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.ray.R;
import com.ray.app.utils.ApplicationUtil;

/**
 * User: Ray
 * Date: 16/3/3
 * ReadMe: Toast-工具类
 */
public class ToastUtil {

    private static Context context = BaseApplication.getInstance();// App生命周期中唯一Context,BaseApplication继承Application
    private static LayoutInflater inflater = LayoutInflater.from(context);// 布局加载
    private static View myToastView = inflater.inflate(R.layout.layout_top_toast, null);
    private static TextView msgView = (TextView) myToastView.findViewById(R.id.tv_msg_text);

    private static final int TYPE_CODE_SUCCESS = 0x01;
    private static final int TYPE_CODE_ERROR = 0x02;
    private static final int COLOR_SUCCESS = context.getResources().getColor(R.color.msg_status_success);
    private static final int COLOR_ERROR = context.getResources().getColor(R.color.msg_status_warn);
    private static final int DEFAULT_TIME_DELAY = 50;// 单位:毫秒

    private static Toast toast;// 系统提示类
    private static Handler handler;

    public static void showSuccessMsg(int msgResId) {
        try {
            showSuccessMsg(context.getString(msgResId));
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void showErrorMsg(int msgResId) {
        try {
            showErrorMsg(context.getString(msgResId));
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void showSuccessMsg(String msg) {
        showMsg(TYPE_CODE_SUCCESS, msg);
    }

    public static void showErrorMsg(String msg) {
        showMsg(TYPE_CODE_ERROR, msg);
    }

    private static void showMsg(final int typeCode, final String msg) {
        if (context == null//
                || !ApplicationUtil.isRunningForeground(context)// 如果APP回到后台,则不显示
                || msg == null) {
            return;
        }

        if (toast == null) {// 防止重复提示:不为Null,即全局使用同一个Toast实例
            toast = new Toast(context);
        }

        if (handler == null) {
            handler = new Handler();
        }

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                int msgViewBagColor = 0;
                switch (typeCode) {
                    case TYPE_CODE_SUCCESS:
                        msgViewBagColor = COLOR_SUCCESS;
                        break;
                    case TYPE_CODE_ERROR:
                        msgViewBagColor = COLOR_ERROR;
                        break;
                    default:
                        msgViewBagColor = COLOR_SUCCESS;
                        break;
                }
                msgView.setBackgroundColor(msgViewBagColor);
                msgView.setText(msg);
                toast.setView(myToastView);
                toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);// 顶部居中
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.show();

            }
        }, DEFAULT_TIME_DELAY);
    }

    // 暂不对外提供:主要针对需要在某个时候,取消提示
    private static void cancelToast() {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
    }
}

3.2、布局文件[ layout_top_toast.xml ]




    

四、Ok,Anyway:

4.1、相关知识点

  • 在实际项目中Toast样式是一致的,也就是说整个APP生命周期内只需要一个Toast实例即可
  • APP中Context的数量=1个Application + n个Activity的数量 + m个Service的数量
  • Toast中使用的Context直接使用Appliction中的Context即可

4.2、会遇到的问题

  • 避免上面所说的多次重复弹出Toast,所以我们将会判断Toast实例是否存在,如果存在直接使用,如果不存在才new

你可能感兴趣的:(Android—App—必备开发组件—通用组件篇—ToastUtil)