以前使用单例toast来保证连续点击不会一直弹toast,代码如下

import android.content.Context;import android.os.Build;import android.widget.Toast;public class ToastUtil {    private static Toast toast;    public static void showToast(Context context, String content, int Duration) {        if (toast == null) {            toast = Toast.makeText(context, content, Duration);        }        else {            toast.setText(content);        }        toast.show();    }    public static void showToast(Context context, int resId, int Duration) {        if (toast == null) {            toast = Toast.makeText(context, context.getResources().getText(resId), Duration);        } else {            toast.setText(context.getResources().getText(resId));        }        toast.show();    }}

但是在android 9.0上运行时发现,上面的代码会导致toast卡顿,第一个显示后再点击就消失了。相反,直接执行Toast.makeText(context, context.getResources().getText(resId), Duration).show(); 反而效果是正确的。没有去看源码,猜想高版本底层做了类似单例的实现。运行各个版本的模拟器测了下,api>=27时可以直接使用Toast.makeText(context, context.getResources().getText(resId), Duration).show();。修改后的ToastUtil:

import android.content.Context;import android.os.Build;import android.util.Log;import android.widget.Toast;public class ToastUtil {    private static Toast toast;    public static void showToast(Context context, String content, int Duration) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {            Toast.makeText(context, content, Duration).show();        } else {            if (toast == null) {                toast = Toast.makeText(context, content, Duration);            } else {                toast.setText(content);            }            toast.show();        }    }    public static void showToast(Context context, int resId, int Duration) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {            Toast.makeText(context, context.getResources().getText(resId), Duration).show();        } else {            if (toast == null) {                toast = Toast.makeText(context, context.getResources().getText(resId), Duration);            } else {                toast.setText(context.getResources().getText(resId));            }            toast.show();        }    }}

上述仅猜想及少量模拟器的测试结果,如有错误恳请指正。

更多相关文章

  1. android获取版本信息、屏幕信息和设备编号
  2. android 100行代码实现 仿苹果滑动选择器WheelView
  3. Android之图文混排 (二)源代码
  4. 一段Android实现应用下载并自动安装apk包的代码
  5. Android统一依赖多个不同版本的Support v7包
  6. 36个Android开发常用代码片段
  7. Android 进阶的小技巧整理(整理自第一行代码)

随机推荐

  1. 我在滴滴数据分析岗实习了8个月
  2. 数据分析师必知的那些Hive-SQL
  3. python连接redis存储
  4. 【点宽专栏】大数据背景下信息所带来的盲
  5. python里使用rabbitmq模块
  6. 磁盘出现“磁盘结构损坏”的解决方法
  7. 比TFLite快2倍!FB开源移动深度学习优化库Q
  8. AI一周热闻:IBM收购Red Hat;马斯克辞去特斯
  9. 通过一个简单的案例看懂量子计算机
  10. 谷歌官宣:全面超越人类的最强NLP预训练模