效果:
工具类MyToast:
package com.example.toastanimation; import android.content.Context; import android.view.WindowManager; import android.widget.Toast; import java.lang.reflect.Field; /** * 自定义动画的Toast */ public class MyToast extends Toast { public MyToast(Context context) { super(context); } /** * 调用有动画的Toast */ public static Toast makeTextAnim(Context context, CharSequence text, int duration,int styleId) { Toast toast = makeText(context, text, duration); toast.setText(text); toast.setDuration(duration); try { Object mTN ; mTN = getField(toast, "mTN"); if (mTN != null) { Object mParams = getField(mTN, "mParams"); if (mParams != null && mParams instanceof WindowManager.LayoutParams) { WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams; params.windowAnimations = styleId; } } } catch (Exception e) { e.printStackTrace(); } return toast; } /** * 反射字段 * @param object 要反射的对象 * @param fieldName 要反射的字段名称 */ private static Object getField(Object object, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field field = object.getClass().getDeclaredField(fieldName); if (field != null) { field.setAccessible(true); return field.get(object); } return null; } }
style.xml中:
<!-- 自定义的Toast动画 --> <style name="Lite.Animation.Toast" parent="@android:style/Animation.Toast"> <item name="android:windowEnterAnimation">@anim/lite_toast_enter</item> <item name="android:windowExitAnimation">@anim/lite_toast_exit</item> </style>
res/anim/lite_toast_enter.xml:
<?xml version="1.0" encoding="utf-8"?> <!-- 进入动画 --> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="@android:integer/config_longAnimTime" android:fromXScale="1" android:toXScale="1" android:fromYScale="0" android:toYScale="1" android:interpolator="@android:anim/decelerate_interpolator" />
res/anim/lite_toast_exit.xml:
<?xml version="1.0" encoding="utf-8"?> <!-- 出去动画 --> <scale xmlns:android="http://schemas.android.com/apk/res/android" android:duration="@android:integer/config_longAnimTime" android:fromXScale="1" android:toXScale="1" android:fromYScale="1" android:toYScale="0" android:interpolator="@android:anim/decelerate_interpolator" />
Toast的用法:
MyToast.makeTextAnim(this, "测试自定义动画Toast", 0,R.style.Lite_Animation_Toast).show();