您的位置:首页 > 移动开发 > Android开发

android Toast显示延迟的优化方案

2014-10-23 11:22 435 查看
在android中,当点击一个按钮显示toast时,若连续点击,那么toast也会一直闪现,当停止点击时还是在显示,为了防止这种情况出现,需要对其进行优化,若直接使用Toast.cancel()方法会不起作用,因此要自定义一个类,将其封装、重写。如下内容
public class ToastUtil { private static Handler handler = new Handler(Looper.getMainLooper()); private static Toast toast = null; private static Object synObj = new Object(); public static void showMessage(final Context act, final String msg) { showMessage(act, msg, Toast.LENGTH_SHORT); } public static void showMessage(final Context act, final int msg) { showMessage(act, msg, Toast.LENGTH_SHORT); } public static void showMessage(final Context act, final String msg, final int len) { new Thread(new Runnable() { public void run() { 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(act, msg, len); } toast.show(); } } }); } }).start(); } public static void showMessage(final Context act, final int msg, final int len) { new Thread(new Runnable() { public void run() { 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(act, msg, len); } toast.show(); } } }); } }).start(); } } 使用时,只需调用该类中的方法即可。虽然感觉逻辑合理,但还是在运行时还是会有bug出现,希望有谁解决掉了可以分享。
转自:http://www.2cto.com/kf/201111/112527.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: