Android中用Toast.cancel()方法最佳化toast內容的顯示

來源:互聯網
上載者:User

產品在測試過程中發現一個bug,就是測試人員不停的瘋狂的點擊某個按鈕,觸發了toast以後,toast內容會一直排著隊的顯示出來,不能很快的消失。這樣可能會影響使用者的使用。

看到Toast有一個cancel()方法:

void cancel()Close the view if it's showing, or don't show it if it isn't showing yet.

做程式員的,基本一看api就知道,用這個可以取消上一個toast的顯示,然後顯示下一個,這樣就能解決出現的問題。可是在測試的過程中,發現卻沒有想象中的那麼簡單,不信可以百度一下,很多很多人發現toast的cancel()方法不起作用。還是不講具體過程,只講結果吧。

我把toast做成了一個應用類,方便使用,大家可以直接用:

 

package com.arui.framework.android.util;import android.content.Context;import android.os.Handler;import android.os.Looper;import android.widget.Toast;
/**    * Toast util class.    *     * @author http://blog.csdn.net/arui319    * @version 2011/11/30    *     */ public class ToastUtil {private static Handler handler = new Handler(Looper.getMainLooper());private static Toast toast = null;private static Object synObj = new Object();public static void showMessage(final Context act, final String msg) {showMessage(act, msg, Toast.LENGTH_SHORT);}public static void showMessage(final Context act, final int msg) {showMessage(act, msg, Toast.LENGTH_SHORT);}public static void showMessage(final Context act, final String msg,final int len) {new Thread(new Runnable() {public void run() {handler.post(new Runnable() {@Overridepublic void run() {synchronized (synObj) {if (toast != null) {toast.cancel();toast.setText(msg);toast.setDuration(len);} else {toast = Toast.makeText(act, msg, len);}toast.show();}}});}}).start();}public static void showMessage(final Context act, final int msg,final int len) {new Thread(new Runnable() {public void run() {handler.post(new Runnable() {@Overridepublic void run() {synchronized (synObj) {if (toast != null) {toast.cancel();toast.setText(msg);toast.setDuration(len);} else {toast = Toast.makeText(act, msg, len);}toast.show();}}});}}).start();}}

 

代碼的邏輯很簡單。這裡加了同步,這樣做可以確保每一個toast的內容至少可以顯示出來,而不是還沒顯示就取消掉了。這樣做,是因為toast的內容不一定完全相同,如果沒顯示出來,也會有問題。

---------------------------------------------------------------------------

GL(arui319)

http://blog.csdn.net/arui319

<本文可以轉載,但是請保留以上作者資訊。謝謝。>

---------------------------------------------------------------------------

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.