ToastUtil工具类代码如下:
public class ToastUtil {
public static void showToast(final Context context, final String msg) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
return;
}
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
});
}
public static void showToast(final Context context, final int msgId) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Toast.makeText(context, msgId, Toast.LENGTH_SHORT).show();
return;
}
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
@Override
public void run() {
Toast.makeText(context, msgId, Toast.LENGTH_SHORT).show();
}
});
}
}
本文介绍了ToastUtil工具类的实现方法,该工具类用于在Android应用中展示短时提示消息。通过两种方法实现了不同场景下的消息显示功能,并考虑了主线程与非主线程的区别。
228

被折叠的 条评论
为什么被折叠?



