自定义Toast

效果图:

这个土司的布局是可以控制的:  分为三种  成功,失败,普通

步骤:

1.创建一个类  继承Application   并将清单文件中Application节点下添加这个类的声明(注意要用全名)

目的: 获取到一个全局的上下文对象

     public class BaseApplication extends Application {
	public static BaseApplication instance;//Application的实例化对象
	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
	}
    }
        <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:name="com.example.defindtoast.BaseApplication">
2.下边是工具类
        /**
         * 自定义土司
         */
        public class CustomToast {
	private static CustomToast customToast;
	private static Toast toast;// 只创建一个Toast的实例化对象
	private View layout;
	private TextView text;
	private ImageView mImageView;

	/**
	 * 使用单例模式只创建一个CustomToast
	 * 
	 * @return
	 */
	public static CustomToast createToast() {
		if (customToast == null)
			customToast = new CustomToast();
		return customToast;
	}

	/**
	 * 展示土司
	 * 
	 * @param context
	 * @param root
	 * @param txt
	 * @param imgResid
	 *            如果是-1 就不显示图片
	 * 
	 */
	@SuppressLint("ResourceAsColor")
	public void show(String txt, int imgResid) {
		if (layout == null) {
			layout = LayoutInflater.from(
					BaseApplication.instance.getApplicationContext()).inflate(
					R.layout.custom_toast, null);
			text = (TextView) layout.findViewById(R.id.text);
			mImageView = (ImageView) layout.findViewById(R.id.iv);
		}
		if (imgResid != -1) {
			mImageView.setBackgroundResource(imgResid);
			mImageView.setVisibility(View.VISIBLE);
		} else {
			mImageView.setVisibility(View.GONE);
		}
		text.setText(txt);
		if (toast == null) {
			toast = new Toast(BaseApplication.instance.getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(layout);
		}
		toast.show();
	}

	/**
	 * 普通消息
	 * 
	 * @param context
	 * @param root
	 * @param text
	 */
	public void showToast(String text) {

		show(text, -1);
	}

	/**
	 * 成功
	 * 
	 * @param context
	 * @param root
	 * @param text
	 */
	public void showSuccess(String text) {
		show(text, R.drawable.toast_success);
	}

	/**
	 * 失败
	 * 
	 * @param context
	 * @param root
	 * @param text
	 */
	public void showFaild(String text) {
		show(text, R.drawable.toast_faild);
	}
}
3.在使用的时候调用就一句话   也可以根据公司业务的需要更改布局,是不是很赞
	   CustomToast.createToast().showToast("普通提示");
         CustomToast.createToast().showSuccess("成功提示");
         CustomToast.createToast().showFaild("失败提示");

   

    点击这里下载源码







































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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值