前言:

一直在考虑写一下Android实际项目中的一些总结,翻看CSDN博客,上一篇已经是一年多曾经。

本系列定位Android基础工具类重构。旨在记录实际项目中经经常使用到的一些工具类,比方Toast、Dialog、动画类,ImageLoader类等等。正在梳理,但发现梳理完再写预计黄花菜都凉了。所以改变策略,边写边梳理。

首先要写的就是这个Toast。

一、说明

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

二、简单使用

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

// 特别说一下:查看源代码会发现makeText方法会返回一个Toast实例,例如以下:

// 由于每次都会new一个新的Toast,这也就是为什么假设同一时候间多次调用makeText会弹出多个提示框。直到全部的提示完毕才消失

源代码:

  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;
}

三、复杂使用

我们看到上图源代码。用到了layout组件。那也就是说我们也能够定义自己的View,Toast提供了在屏幕上的显示位置。

这样我们就能够自己定义自己的样式的而且在须要的位置显示的Toast。见四

四、实际项目中使用

4.1、相关知识点

1)在实际项目中Toast样式是一致的,也就是说整个APP生命周期内仅仅须要一个Toast实例就可以

2)Toast中使用的Context直接使用Appliction中的Context就可以。

由于APP中Context的数量=1个Application + n*Activity的数量 + m*Service的数量

4.2、会遇到的问题

避免上面所说的多次反复弹出Toast,所以我们将会推断Toast实例是否存在,假设存在直接使用。假设不存在才new

4.3、效果

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

4.4、话不多说,上代码

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;
}
}
}

<?xml version="1.0" encoding="utf-8"?

>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"> <TextView
android:id="@+id/tv_msg_text"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_height"
android:background="@color/msg_status_success"
android:ellipsize="end"
android:gravity="center"
android:maxLines="2"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="@color/white"
android:textSize="16dp" />
</RelativeLayout>

五、Android5.0官方新替代组件

眼下市面上未见有太多使用,兴许补充。

。。

Android基础工具类重构系列一Toast的更多相关文章

  1. Android 常见工具类封装

    1,MD5工具类: public class MD5Util { public final static String MD5(String s) { char hexDigits[] = { '0' ...

  2. (转载)android 一些工具类汇总

    android 一些工具类汇总 作者:曾田生z 字体:[增加 减小] 类型:转载 时间:2016-08-14我要评论 本文给大家汇总介绍了一些常用的Android工具类,非常的简单实用,有需要的小伙伴 ...

  3. 53. Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefer ...

  4. 【转】Android常用工具类

    主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.Prefe ...

  5. Android自定义工具类获取按钮并绑定事件(利用暴力反射和注解)

    Android中为按钮绑定事件的有几种常见方式,你可以在布局文件中为按钮设置id,然后在MainActivity中通过findViewById方法获取按钮对象实例,再通过setOnClickListe ...

  6. Android 常用工具类之SPUtil,可以修改默认sp文件的路径

    参考: 1. 利用Java反射机制改变SharedPreferences存储路径    Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import ...

  7. Android常见工具类封装

    MD5加密 import android.annotation.SuppressLint; import java.security.MessageDigest; public class MD5 { ...

  8. android开发工具类总结(一)

    一.日志工具类 Log.java public class L { private L() { /* 不可被实例化 */ throw new UnsupportedOperationException ...

  9. android常用工具类

    import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkIn ...

随机推荐

  1. 【php】基础学习1

    其中包括php基础.字符串和正则表达式的学习.具体如下: <html xmlns=http://www.w3.org/1999/xhtml> <head> <meta h ...

  2. 什么是Asterisk,它如何帮助我们的呼叫中心?

    如今的呼叫中心与过去的呼叫中心有很大差异.过去,一间房屋或一座大楼,装上硬接线的POTS电话,招聘几名员工就可以建立一个呼叫中心.如今,这样的情形已经一去不复返,因为有许多新技术让呼叫中心变得更像是一 ...

  3. PMP_PMP考试须知

    考试报名 按照报名须知和填表指南中的要求提交报名材料同时交纳考试费用.北京地区的考生直接到国家外国专家局培训中心报名:外地考生到所在地报名点报名:未设有报名点的地区,可直接与国家外国专家局培训中心联系 ...

  4. Workflow_工作流的基本概念(概念)

    2014-06-01 Created By BaoXinjian

  5. SpringMVC中异常处理详解

    Spring MVC处理异常最基本的就是HandlerExceptionResolver这个接口,先看张图 分析上图可以轻松总结出,spring mvc里有三种异常处理方法: 1.使用官方提供的简单异 ...

  6. jquery动态加载js三种方法实例

    这里为你提供了三种动态加载js的jquery实例代码哦,由于jquery是为用户提供方便的,所以利用jquery动态加载文件只要一句话$.getScript(\"test.js\" ...

  7. Amoeba软件实现mysql读写分离

    一般不用,大公司都是自己程序实现的. 安装amoeba

  8. Cocos2d-x CCScale9Sprite 用法

    1.创建方式有三种: (1).直接创建 auto blocks = Scale9Sprite::create("blocks9.png", Rect(0, 0, 96, 96), ...

  9. Django---MTV模型、基本命令、简单配置

    MTV模型 Django的MTV分别代表: Model(模型):负责业务对象与数据库的对象(ORM) Template(模版):负责如何把页面展示给用户 View(视图):负责业务逻辑,并在适当的时候 ...

  10. Ngen.exe和本机映像缓存

    本机映像生成器创建托管程序集的本机映像,并且将该映像安装到本地计算机的本机映像缓存中.本机映像缓存是全局程序集缓存的保留区域.一旦您为某个程序集创建了本机映像,运行库在每次运行该程序集时就会自动使用该 ...