Android中使用Toast.cancel()方法優(yōu)化toast內(nèi)容顯示的解決方法
更新時間:2013年05月10日 08:56:26 作者:
做程序員的,基本一看api就知道,用這個可以取消上一個toast的顯示,然后顯示下一個,這樣就能解決出現(xiàn)的問題。可是在測試的過程中,發(fā)現(xiàn)卻沒有想象中的那么簡單,不信可以百度一下,很多很多人發(fā)現(xiàn)toast的cancel()方法不起作用
產(chǎn)品在測試過程中發(fā)現(xiàn)一個bug,就是測試人員不停的瘋狂的點擊某個按鈕,觸發(fā)了toast以后,toast內(nèi)容會一直排著隊的顯示出來,不能很快的消失。這樣可能會影響用戶的使用。
看到Toast有一個cancel()方法:
復制代碼 代碼如下:
void cancel()
Close the view if it's showing, or don't show it if it isn't showing yet.
做程序員的,基本一看api就知道,用這個可以取消上一個toast的顯示,然后顯示下一個,這樣就能解決出現(xiàn)的問題??墒窃跍y試的過程中,發(fā)現(xiàn)卻沒有想象中的那么簡單,不信可以百度一下,很多很多人發(fā)現(xiàn)toast的cancel()方法不起作用。還是不講具體過程,只講結(jié)果吧。
我把toast做成了一個應(yīng)用類,方便使用,大家可以直接用:
復制代碼 代碼如下:
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 <A >http://jb51.net</A>
* @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() {
@Override
public 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() {
@Override
public 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的內(nèi)容至少可以顯示出來,而不是還沒顯示就取消掉了。這樣做,是因為toast的內(nèi)容不一定完全相同,如果沒顯示出來,也會有問題。
相關(guān)文章
Android RecyclerView添加頭部和底部的方法
這篇文章主要為大家詳細介紹了Android RecyclerView添加頭部和底部的方法,感興趣的小伙伴們可以參考一下2016-05-05
android使用gesturedetector手勢識別示例分享
這篇文章主要介紹了android使用手勢識別的方法,介紹了單擊觸摸屏觸發(fā)的事件和雙擊事件的使用等方法,大家參考使用吧2014-01-01
Android實現(xiàn)自動點擊無障礙服務(wù)功能的實例代碼
這篇文章主要介紹了Android實現(xiàn)自動點擊無障礙服務(wù)功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
Android studio將Module打包成Jar的方法
這篇文章主要介紹了Android studio將Module打包成Jar的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10

