Toast 在android 4.0中问题解决方案
androidandroid 4.0Toast
Toast 在android 4.0中问题解决方案。
自己实现Toast 使用WindowManager 绘制在屏幕上
使用handler计时 消除Toast
可以解决 Toast 在4.0中无法连续触发(在队列中一个个显示,会造成大量延时) cancel导致的异常(不正常显示、延时显示、不显示)等问题
存在问题:必须使用Activity的context对象创建Toast 所以在service中无法使用
:有可能会与其他的使用WindowManager的操作产生冲突
其他方案:Toast源码中是使用WindowManagerImpl来操作的 基本方法一致
但是此类在framework源文件中存在 SDK中却找不到
在网上搜寻资料得知,这个类时隐藏的,要和android源码一起编译才能使用。
目前还不知道怎么弄
- package dk.toasttest;
- import android.content.Context;
- import android.graphics.PixelFormat;
- import android.os.Handler;
- import android.os.Message;
- import android.view.Gravity;
- import android.view.WindowManager;
- import android.widget.TextView;
- import android.widget.Toast;
- /**
复制代码 *
* @author DK
* App内所有Toast均使用本类管理
* 每个触发的Toast都会显示
*
* 不存在延迟Toast现象
*/- public class ToastUtil {
- public static TextView tv;
- public static WindowManager mWindowManager;
- 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, act.getString(msg), Toast.LENGTH_SHORT);
- }
-
- public static void showMessage(Context context,String msg,int Length)
- {
- if(tv==null)
- {
- tv=new TextView(context);
- tv.setText("msg");
- tv.setTextSize(24);
- tv.setBackgroundResource(R.drawable.bg_layoutinput_focused);
- tv.setPadding(0, 0, 0, 30);
- }
-
- if(tv.getParent()==null)
- {
- WindowManager.LayoutParams params = new WindowManager.LayoutParams();
- params.gravity = Gravity.BOTTOM;
- params.alpha = 0.65f;
- params.x = 0;
- params.height = WindowManager.LayoutParams.WRAP_CONTENT;
- params.width = WindowManager.LayoutParams.WRAP_CONTENT;
- params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
- | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
- | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
- params.format = PixelFormat.TRANSLUCENT;
- params.windowAnimations = 0;
- mWindowManager.addView(tv, params);
- handler.sendEmptyMessageDelayed(101, 5000);
- }
- else
- {
- tv.setText(msg);
- handler.removeMessages(101);
- handler.sendEmptyMessageDelayed(101, 5000);
- }
- }
-
-
- static Handler handler =new Handler(){
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- if(tv.getParent()!=null)
- mWindowManager.removeView(tv);
- }
-
-
- };
-
- public static void cancelCurrentToast()
- {
- if(tv!=null && tv.getParent()!=null)
- {
- mWindowManager.removeView(tv);
- }
- }
- }
复制代码 |