自定义Toast 可以根据自己的需求 设置显示时间

[java]  view plain  copy
 print ?
  1. package com.elite;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5.   
  6. import android.content.Context;  
  7. import android.os.Handler;  
  8. import android.view.Gravity;  
  9. import android.widget.Toast;  
  10.   
  11. public class Toasts {  
  12.     private Toast toast;  
  13.     private Field field;  
  14.     private Object obj;  
  15.     private Method showMethod;  
  16.     private Method hideMethod;  
  17.     private int time;  
  18.   
  19.     public Toasts(Context c, String text,int time) {  
  20.         toast = Toast.makeText(c, text, time);  
  21.         toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL,  
  22.                 00);  
  23.         this.time=time;  
  24.         reflectionTN();  
  25.     }  
  26. public void show(){  
  27.     toast.show();  
  28.     Handler handler = new Handler();  
  29.     handler.postDelayed(new Runnable() {  
  30.   
  31.         @Override  
  32.         public void run() {  
  33.             try {  
  34.                 hideMethod.invoke(obj, null);// 调用TN对象的hide()方法,关闭toast  
  35.             } catch (Exception e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.     }, time);  
  40.       
  41. }  
  42.     private void reflectionTN() {  
  43.         try {  
  44.             field = toast.getClass().getDeclaredField("mTN");  
  45.             field.setAccessible(true);  
  46.             obj = field.get(toast);  
  47.             showMethod = obj.getClass().getDeclaredMethod("show"null);  
  48.             hideMethod = obj.getClass().getDeclaredMethod("hide"null);  
  49.         } catch (Exception e) {  
  50.             e.printStackTrace();  
  51.         }  
  52.     }  
  53.   
  54. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值