Android 自定义Toast ,并且控制显示时间

今天需求提出定义Toast时间的蛋疼需求,以前也接触过这方面 但是没有详细搞过,所以也遇到了一点波折,废话不多说了 上代码吧

  1 /**
  2  * Copyright (C) 2014 Luki(liulongke@gmail.com)
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      http://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 package ********;
 17 
 18 import android.content.Context;
 19 import android.graphics.PixelFormat;
 20 import android.os.Handler;
 21 import android.os.Message;
 22 import android.view.Gravity;
 23 import android.view.View;
 24 import android.view.WindowManager;
 25 import android.widget.Toast;
 26 
 27 import java.util.Timer;
 28 import java.util.TimerTask;
 29 
 30 import *****.R;
 31 import luki.x.base.XLog;
 32 
 33 /**
 34  * 自定义Toast
 35  */
 36 public class ToastCustom extends Toast {
 37 
 38     private WindowManager mWindowManager;
 39     private int mDuration;
 40     private View mView;
 41     private WindowManager.LayoutParams mParams;
 42     private Timer mTimer;
 43     private static ToastCustom mToast;
 44     private boolean isShow;
 45 
 46     private static final Handler mDismissHandler = new Handler() {
 47         @Override
 48         public void handleMessage(Message msg) {
 49             ToastCustom toastCustom = (ToastCustom) msg.obj;
 50             try {
 51                 toastCustom.mWindowManager.removeView(toastCustom.mView);
 52             } catch (Exception e) {
 53                 XLog.w("ToastCustom", e.toString());
 54             }
 55             toastCustom.isShow = false;
 56         }
 57     };
 58 
 59     private ToastCustom(Context context, CharSequence text, int duration) {
 60         super(context);
 61         mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
 62         mTimer = new Timer();
 63 
 64         setView(View.inflate(context, R.layout.dialog_alert_message, null));
 65         setText(text);
 66         setDuration(duration);
 67 
 68         mParams = new WindowManager.LayoutParams();
 69         mParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
 70         mParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
 71         mParams.format = PixelFormat.TRANSLUCENT;
 72         mParams.windowAnimations = android.R.style.Animation_Toast;
 73         mParams.type = WindowManager.LayoutParams.TYPE_TOAST;
 74         mParams.setTitle("Toast");
 75         mParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
 76         mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
 77     }
 78 
 79     /**
 80      *  创建一个Toast
 81      * @param context context
 82      * @param text text 显示文字
 83      * @param duration duration 显示时间 秒 例如:1 代表1秒
 84      * @return ToastCustom
 85      */
 86     public static ToastCustom getInstance(Context context, CharSequence text, int duration) {
 87         if (mToast == null) {
 88             mToast = new ToastCustom(context, text, duration);
 89         } else {
 90             mToast.setText(text);
 91             mToast.setDuration(duration);
 92         }
 93         return mToast;
 94     }
 95 
 96     /**
 97      * 设置自定义View 但是view里面一定到包含一个android.R.id.message的TextView控件
 98      * @param view 自定义View
 99      */
100     public void setView(View view) {
101         super.setView(view);
102         if (mView != null) {
103             try {
104                 mWindowManager.removeView(mView);
105             } catch (Exception e) {
106                 XLog.w("ToastCustom", e.toString());
107             }
108         }
109         mView = view;
110     }
111 
112     /**
113      * 设置显示时间
114      * @param duration 显示时间 秒 例如:1 代表1秒
115      */
116     @Override
117     public void setDuration(int duration) {
118         super.setDuration(duration);
119         mDuration = duration;
120     }
121 
122     /**
123      * Set the location at which the notification should appear on the screen.
124      * @see android.view.Gravity
125      * @see #getGravity
126      */
127     @Override
128     public void setGravity(int gravity, int xOffset, int yOffset) {
129         super.setGravity(gravity, xOffset, yOffset);
130         mParams.gravity = gravity;
131         mParams.x = xOffset;
132         mParams.y = yOffset;
133     }
134 
135     /**
136      * Set the margins of the view.
137      *
138      * @param horizontalMargin The horizontal margin, in percentage of the
139      *        container width, between the container's edges and the
140      *        notification
141      * @param verticalMargin The vertical margin, in percentage of the
142      *        container height, between the container's edges and the
143      *        notification
144      */
145     @Override
146     public void setMargin(float horizontalMargin, float verticalMargin) {
147         super.setMargin(horizontalMargin, verticalMargin);
148         mParams.horizontalMargin = horizontalMargin;
149         mParams.verticalMargin = verticalMargin;
150     }
151 
152     /**
153      * 显示Toast,没有将这个Toast放入系统的队列中,自己来管理显示与消失
154      */
155     public void show() {
156         if (!isShow) {
157             isShow = true;
158             mWindowManager.addView(mView, mParams);
159         }
160         try {
161             mTimer.cancel();
162         } catch (Exception e) {
163             XLog.w("ToastCustom", e.toString());
164         }
165         mTimer = new Timer();
166         mTimer.schedule(new TimerTask() {
167             @Override
168             public void run() {
169                 ToastCustom.this.cancel();
170             }
171         }, (long) (mDuration * 1000));
172     }
173 
174     /**
175      * 取消Toast
176      */
177     public void cancel() {
178         mDismissHandler.obtainMessage(0, this).sendToTarget();
179     }
180 
181 }

然后上布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/dialog_corner_black_trans"
    android:orientation="horizontal" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/dialog_notify" />

    <TextView
        android:id="@android:id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_16sp" />

</LinearLayout>

 

posted @ 2015-08-25 17:14  一心要吵闹  阅读(1154)  评论(0)    收藏  举报