Android 弹toast工具类

我们在程序中经常会有弹出一个toast的需求,而如果每一次都对toast创建出一个新的对象并描述,这样不仅浪费资源而且浪费我们的编码时间。

这是一个工具类,我们需要弹出toast的时候,只要调用XToaster.show方法就能简单地实现toast弹出。


package com.utils.tools;

import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;

public class XToaster {

	private static Toast mToast;
	
	private XToaster() {}
	
	@SuppressLint("ShowToast")
	public synchronized static void init(Context ctx) {
		if (mToast == null) mToast = Toast.makeText(ctx, "", Toast.LENGTH_LONG);
	}
	
	public static void show(final int resId) {
		if (mToast == null) throw new NullPointerException("XToaster is not init");
		
		String msg = mToast.getView().getContext().getString(resId);
		show(msg);
	}
	
	public static void show(final CharSequence msg) {
		if (mToast == null) throw new NullPointerException("XToaster is not init");
		
		mToast.setText(msg);
		mToast.setDuration(Toast.LENGTH_SHORT);  
		mToast.show(); 	
	}
	
	public static void showPost(final CharSequence msg) {
		if (mToast == null) throw new NullPointerException("XToaster is not init");
		
		mToast.getView().post(new XuRunnable(msg));
	}
	
	public static void show(final CharSequence msg, int delay) {
		if (mToast == null) throw new NullPointerException("XToaster is not init");
		
		mToast.getView().postDelayed(new XuRunnable(msg), delay);
	}
	
	private static class XuRunnable implements Runnable {

		private CharSequence _msg;

		public XuRunnable(CharSequence msg) {
			_msg = msg;
		}

		@Override
		public void run() {
//			mToast.cancel();  
			mToast.setText(_msg);  
			mToast.setDuration(Toast.LENGTH_SHORT);  
			mToast.show(); 			
		}
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值