码迷,mamicode.com
首页 > 其他好文 > 详细

4:Toast类封装

时间:2017-11-11 11:26:46      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:otto   author   you   .sh   bottom   color   static   class   sage   

1:ToastUtil.java

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cqsl.pay.R;

/**
 * Toast提示工具类
 * @author baoxl
 *
 */
public class ToastUtil {
    private static final long TOAST_THRESHOLD = 2000;
    private static long previous = 0;
    private static Toast toast;
    private static Context context;
    private static TextView tipTv;

    private ToastUtil() {}
    
    public static void init(Context ctx) {
        context = ctx;
    }

    public static void toast(String message) {
        toast(message, Toast.LENGTH_LONG);
    }

    public static void toast(int id) {
        toast(id, Toast.LENGTH_LONG);
    }

    public static void toast(int id, int duration) {
        String message = context.getString(id);
        toast(message, duration);
    }

    public static void toast(String text, int duration) {
        long now = System.currentTimeMillis();
        if (now - previous < TOAST_THRESHOLD) {
            tipTv.setText(text);
            toast.show();
        } else {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
            tipTv = (TextView) view.findViewById(R.id.toast_text);
            tipTv.setText(text);
            toast.setDuration(duration);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.setView(view);
            toast.show();
        }
        previous = now;
    }
    
    public static void toast(String text, int duration, int xOffset, int yOffset) {
        long now = System.currentTimeMillis();
        if (now - previous < TOAST_THRESHOLD) {
            tipTv.setText(text);
            toast.show();
        } else {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
            tipTv = (TextView) view.findViewById(R.id.toast_text);
            tipTv.setText(text);
            toast.setDuration(duration);
            toast.setView(view);
            toast.setGravity(Gravity.NO_GRAVITY, xOffset, yOffset);
            toast.show();
        }
        previous = now;
    }
    
    public static void cancel() {
        if (toast != null) {
            toast.cancel();
        }
    }
}

 

4:Toast类封装

标签:otto   author   you   .sh   bottom   color   static   class   sage   

原文地址:http://www.cnblogs.com/wnpp/p/7817321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!