Android自定义Toast工具类


public class ToastUtil {

private static Handler handler = new Handler(Looper.getMainLooper());

private static Toast toast = null;

private final static Object synObj = new Object();

private static Toast toastCenter = null;

/**
* 弹出自定义toast
* @param msg 消息内容
* @param duration 消息显示时长
*/
public static void showMessageCenter(final String msg, final int duration){
if(null == toastCenter){
LayoutInflater inflater = LayoutInflater.from(BaseApplication.getInstance().getApplicationContext());
View layout = inflater.inflate(R.layout.toast_center_custom, null);
toastCenter = new Toast(BaseApplication.getInstance().getApplicationContext());
toastCenter.setView(layout);
}
toastCenter.setDuration(duration);
toastCenter.setGravity(Gravity.CENTER, 0, 0);
((TextView)toastCenter.getView().findViewById(R.id.toast_message)).setText(msg);
toastCenter.show();
}

public static void showMessage(final CharSequence msg) {
showMessage(msg, Toast.LENGTH_SHORT);
}

/**
* 根据设置的文本显示
* @param msg
*/
public static void showMessage(final int msg) {
showMessage(msg, Toast.LENGTH_SHORT);
}

/**
* 显示一个文本并且设置时长
* @param msg
* @param len
*/
public static void showMessage(final CharSequence msg, final int len) {
if (msg == null || msg.equals("")) {
return;
}
handler.post(new Runnable() {
@Override
public void run() {
synchronized (synObj) { //加上同步是为了每个toast只要有机会显示出来
if (toast != null) {
//toast.cancel();
toast.setText(msg);
toast.setDuration(len);
} else {
toast = Toast.makeText(BaseApplication.getInstance(), msg, len);
}
toast.show();
}
}
});
}

public static void showMessageForGravity(final CharSequence msg) {
if (msg == null || msg.equals("")) {
return;
}
handler.post(new Runnable() {
@Override
public void run() {
synchronized (synObj) { //加上同步是为了每个toast只要有机会显示出来
if (toast != null) {
//toast.cancel();
toast.setText(msg);
toast.setDuration(Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(BaseApplication.getInstance(), msg, Toast.LENGTH_SHORT);
}
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
}
}
});
}

/**
* 资源文件方式显示文本
* @param msg
* @param len
*/
public static void showMessage(final int msg, final int len) {
handler.post(new Runnable() {
@Override
public void run() {
synchronized (synObj) {
if (toast != null) {
//toast.cancel();
toast.setText(msg);
toast.setDuration(len);
} else {
toast = Toast.makeText(BaseApplication.getInstance(), msg, len);
}
toast.show();
}
}
});
}

public static void showMessage(final View v, final CharSequence msg) {
((TextView) v).setText(msg);
}
}

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注