/**
* //带图片的吐司窗体
*
* @param context 上下文
* @param message 吐司内容
* @param imageId 图片ID
*/
public static void ToastWithImage(final Context context, final Object message, int imageId) {
Toast toast = Toast.makeText(context.getApplicationContext(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
if (imageId != 0) {
ImageView imageCodeProject = new ImageView(context.getApplicationContext());
imageCodeProject.setImageResource(imageId);
toastView.addView(imageCodeProject, 0);
toast.show();
}
if (imageId == 0) {
toast.show();
}
}
/**
* 快速快速toast 让其在主线程进行
*
* @param mContext
* @param msg
*/
public static void showToast(final Context mContext, final String msg) {
try {
if (Looper.getMainLooper() == Looper.myLooper()) {
//说明是在主线程
safeToast(mContext, msg);
} else {
//说明不是在主线程
if (handler == null) {
handler = new Handler(Looper.getMainLooper());
}
handler.post(new Runnable() {
@Override
public void run() {
safeToast(mContext, msg);
// toast(mContext, msg);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 安全的toast 避免内存溢出
*
* @param mContext
* @param msg
*/
private static void safeToast(Context mContext, String msg) {
try {
if (mToast == null || mToast.get() == null) {
mToast = new SoftReference<Toast>(Toast.makeText(mContext, msg, Toast.LENGTH_SHORT));
}
mToast.get().setText("" + msg);
mToast.get().show();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param mContext
* @param msg
*/
private static void toast(Context mContext, String msg) {
if (toast == null) {
toast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
}
toast.setText(msg);
toast.show();
}
Android工具类之 toast
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 短信分享 邮件分享 短信分享 短信分享2 上边的短信分享在华为手机上分享会没有内容,因此采用下边的方法,亲测华为手...
- 前言 相信大部分仁兄在使用系统Toast的时候,都感觉不太尽如人意,因为系统Toast显示的位置比较固定,并且字体...