这是一个通用的Toast提示消息框
/**
* 这是一个通用的Toast提示消息框
*
* @author wangll
*
*/
public class UtilToast {
//显示时间
public static final int LENGTH_SHORT = 600;
public static final int LENGTH_LONG = 1200;
//Toast背景,这里只写最常见的灰色半透明
public static final Style STYLE_ERROR = new Style(LENGTH_LONG, R.drawable.toast_shap);
public static final Style STYLE_ALERT = new Style(LENGTH_LONG, R.drawable.toast_alert);
public static final Style STYLE_CONFIRM = new Style(LENGTH_SHORT, R.drawable.toast_confirm);
public static final Style STYLE_INFO = new Style(LENGTH_SHORT, R.drawable.toast_info);
private static Toast toast;
/**
* 显示一个提示框,一般用于状态提示,如成功后,显示什么,失败后显示什么
*
* @param ctx 上下文
* @param message 消息内容
* @param isSucc 是否成功
*/
public static void show(Context ctx, String message, Style style) {
if (null == ctx)
return;
LayoutInflater inflate = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(R.layout.layout_toast, null);
v.setBackgroundResource(style.background);
TextView tv = (TextView) v.findViewById(android.R.id.message);
tv.setText(message);
if (toast != null)
{
toast.cancel();
}
toast = new Toast(ctx);
toast.setGravity(Gravity.BOTTOM, 0, Common.getPixels(ctx, 100));
toast.setDuration(style.duration);
toast.setView(v);
toast.show();
}
public static class Style {
private final int duration;
private final int background;
public Style(int duration, int resId) {
this.duration = duration;
this.background = resId;
}
public int getDuration() {
return duration;
}
public int getBackground() {
return background;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof UtilToast.Style)) {
return false;
}
Style style = (Style) o;
return style.duration == duration && style.background == background;
}
}
public static void cancelToast()
{
if (toast != null)
{
toast.cancel();
}
}
}
接着写Toast背景( R.drawable.toast_shap),自定义圆角灰色半透明背景
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#80000000"/>
<stroke android:width="1dip" />
<corners android:radius="90dp"/>
<padding android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"/>
</shape>
引用:
UtilToast.show(this, “显示的内容”, UtilToast.STYLE_ALERT);