Toast的动画效果

效果:


工具类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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值