Android之Toast自定義動畫
阿新 • • 發佈:2019-02-07
參考出處:http://www.cnblogs.com/net168/p/4237528.html
(會出現窗體洩漏has leaked window) 避免線上程中removeView
public class MyToast { boolean mShowTime; boolean mIsShow; WindowManager mWdm; Timer mTimer; View mToastView; WindowManager.LayoutParams mParams; public MyToast(Context context, String text, boolean showTime) { mShowTime = showTime;//記錄Toast的顯示長短型別 mIsShow = false;//記錄當前Toast的內容是否已經在顯示 mWdm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); mToastView = Toast.makeText(context, text, Toast.LENGTH_SHORT).getView();//通過Toast例項獲取當前android系統的預設Toast的View佈局 mTimer = new Timer(); setParams(); } /** * 設定佈局引數 */ private void setParams() { mParams = new WindowManager.LayoutParams(); mParams.height = WindowManager.LayoutParams.WRAP_CONTENT; mParams.width = WindowManager.LayoutParams.WRAP_CONTENT; mParams.format = PixelFormat.TRANSLUCENT; mParams.windowAnimations = R.style.anim_view;//設定進入退出動畫效果 mParams.type = WindowManager.LayoutParams.TYPE_TOAST; mParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; mParams.gravity = Gravity.BOTTOM;//位置 mParams.y = 50; } public static MyToast makeText(Context context, String text, boolean showTime) { MyToast result = new MyToast(context, text, showTime); return result; } /** * 此處修改 以免造成窗體洩漏 */ public void show() { if (!mIsShow) { mIsShow = true; mWdm.addView(mToastView, mParams); mTimer.schedule(new TimerTask() { @Override public void run() { mHandler.sendEmptyMessage(1); } }, (long) (mShowTime ? 1500 : 1500)); } } Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mWdm.removeViewImmediate(mToastView); mIsShow = false; super.handleMessage(msg); } }; }