- package com.elite;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import android.content.Context;
- import android.os.Handler;
- import android.view.Gravity;
- import android.widget.Toast;
- public class Toasts {
- private Toast toast;
- private Field field;
- private Object obj;
- private Method showMethod;
- private Method hideMethod;
- private int time;
- public Toasts(Context c, String text,int time) {
- toast = Toast.makeText(c, text, time);
- toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL,
- 0, 0);
- this.time=time;
- reflectionTN();
- }
- public void show(){
- toast.show();
- Handler handler = new Handler();
- handler.postDelayed(new Runnable() {
- @Override
- public void run() {
- try {
- hideMethod.invoke(obj, null);// 调用TN对象的hide()方法,关闭toast
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }, time);
- }
- private void reflectionTN() {
- try {
- field = toast.getClass().getDeclaredField("mTN");
- field.setAccessible(true);
- obj = field.get(toast);
- showMethod = obj.getClass().getDeclaredMethod("show", null);
- hideMethod = obj.getClass().getDeclaredMethod("hide", null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
自定义Toast 可以根据自己的需求 设置显示时间
猜你喜欢
转载自blog.csdn.net/nihb1/article/details/50764464
今日推荐
周排行