您的位置:首页 > 其它

Toast 自定义Toast工具类

2015-06-12 16:35 183 查看
功能说明:
1 可以实现Toast 有图 UI可以自定义 圆角可变 位置自定义
2 可以实现有无图切换
3 多次点击 不重复

/**

* 吐司工具

*

* @author color

*/
public
class ToastUtils {

private static Toast mToast;

private static String lastToast =
"";

private static
long lastToastTime;

private ToastUtils() {

}

public static
void show(Context context, String msg) {

if (mToast == null) {
mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
}
else {
mToast.setText(msg);
mToast.setDuration(Toast.LENGTH_SHORT);
}
mToast.show();
}

// public static void showIcon(Context context, String msg) {

// mToast = Toast.makeText(context,

// msg, Toast.LENGTH_LONG);

// mToast.setGravity(Gravity.CENTER, 0, 0);

// LinearLayout toastView = (LinearLayout) mToast.getView();

// ImageView imageCodeProject = new ImageView(context);

// imageCodeProject.setImageResource(R.drawable.wz_toast_logo);

// toastView.addView(imageCodeProject, 0);

// mToast.show();

// }

public static
void showToastShort(Context context,String message) {
showBaseToast(message, Toast.LENGTH_SHORT,
0, Gravity.BOTTOM, context);
}

public static
void showToastIcon(Context context,String message,
int icon) {
showBaseToast(message, Toast.LENGTH_LONG, icon, Gravity.CENTER, context);
}

private static
void showBaseToast(String message,
int duration, int icon,
int gravity, Context context) {

if (!TextUtils.isEmpty(message)) {

long time = System.currentTimeMillis();

if (!message.equalsIgnoreCase(lastToast)
|| Math.abs(time - lastToastTime) >
2000) {
View view = LayoutInflater.from(context).inflate(R.layout.wz_toast_view,
null);
((TextView) view.findViewById(R.id.tvForToast)).setText(message);

if (icon != 0) {
((ImageView) view.findViewById(R.id.ivForToast))
.setImageResource(icon);
(view.findViewById(R.id.ivForToast))
.setVisibility(View.VISIBLE);
}else{
(view.findViewById(R.id.ivForToast))
.setVisibility(View.GONE);
}
Toast toast =
new Toast(context);
toast.setView(view);

if (gravity == Gravity.CENTER) {
toast.setGravity(gravity,
0, 0);
}
else {
toast.setGravity(gravity,
0, 35);
}

toast.setDuration(duration);
toast.show();
lastToast = message;
lastToastTime = System.currentTimeMillis();
}
}
}

public void cancelToast() {

if (mToast != null) {
mToast.cancel();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: