您的位置:首页 > Web前端 > CSS

自定义Toast,防止层叠显示问题,和自定义Toast样式

2016-06-17 13:51 711 查看
做Android开的人都应该知道,Android原生Toast在短时间多次show的情况下会出现层叠和重复显示问题,即使APP整个进程被杀了,Toast还是会一直显示直至你最后一个Toast显示完,本文就是针对此问题给出了一个个人的解决办法,先看代码:<span style="font-family:SimSun;font-size:14px;"> public static void showShort(Context mcContext, String msg) {
if (null == mToast) {
mToast = Toast.makeText(mcContext, msg, Toast.LENGTH_SHORT);
// mToast.setGravity(Gravity.BOTTOM, 0, 350);
} else {
mToast.setText(msg);
}
mToast.show();
}</span>

原理就是利用单例模式,不让Toast重复new 对象,这样不仅省资源,而且也避免了重复弹出的问题

1.默认效果:




代码:
Toast.makeText(getApplicationContext(), "默认Toast样式",
Toast.LENGTH_SHORT).show();

2.自定义显示位置效果:




代码:
toast = Toast.makeText(getApplicationContext(),
"自定义位置Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

 3.带图片效果:




代码
toast = Toast.makeText(getApplicationContext(),
"带图片的Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.drawable.icon);
toastView.addView(imageCodeProject, 0);
toast.show();

4.完全自定义效果:




代码
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom,
(ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout
.findViewById(R.id.tvImageToast);
image.setImageResource(R.drawable.icon);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("完全自定义Toast");
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

5.其他线程:





 代码:
<span style="font-family:SimSun;">new Thread(new Runnable() {
public void run() {
showToast();
}
}).start();</span>源码下载:下载源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息