android高版本Toast问题
16lz
2021-01-23
以前使用单例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(); } }}
上述仅猜想及少量模拟器的测试结果,如有错误恳请指正。
更多相关文章
- android获取版本信息、屏幕信息和设备编号
- android 100行代码实现 仿苹果滑动选择器WheelView
- Android之图文混排 (二)源代码
- 一段Android实现应用下载并自动安装apk包的代码
- Android统一依赖多个不同版本的Support v7包
- 36个Android开发常用代码片段
- Android 进阶的小技巧整理(整理自第一行代码)