Android之Toast簡單實現不迴圈提示

來源:互聯網
上載者:User

不知道各位程式猿們在項目中有沒有遇到這個問題:點擊一個view彈出一個Toast,我們用的方法是Toast.makeText(context, "提示", Toast.LENGTH_SHORT).show(); 但是,細心的人發現了,如果頻繁的點擊這個view,會發現儘管我們退出了這個應用,還是會一直彈出提示,這顯然是有點點小尷尬和惱人的。下面就給大家提供兩種方式解決這個問題。

1.封裝了一個小小的Toast:

/** * 不迴圈提示的Toast * @author way * */public class MyToast {Context mContext;Toast mToast;public MyToast(Context context) {mContext = context;mToast = Toast.makeText(context, "", Toast.LENGTH_SHORT);mToast.setGravity(17, 0, -30);//置中顯示}public void show(int resId, int duration) {show(mContext.getText(resId), duration);}public void show(CharSequence s, int duration) {mToast.setDuration(duration);mToast.setText(s);mToast.show();}public void cancel() {mToast.cancel();}}

2.兩個直接調用的函數函數:可以放在在Activity中,在需要時直接調用showToast(String or int); 在Activity的onPause()中調用hideToast(),使得應用退出時,取消掉惱人的Toast。

/** * Show a toast on the screen with the given message. If a toast is already * being displayed, the message is replaced and timer is restarted. *  * @param message *            Text to display in the toast. */private Toast toast;private void showToast(CharSequence message) {    if (null == toast) {        toast = Toast.makeText(this, message,                Toast.LENGTH_LONG);        toast.setGravity(Gravity.CENTER, 0, 0);    } else {        toast.setText(message);    }     toast.show();} /** Hide the toast, if any. */private void hideToast() {    if (null != toast) {        toast.cancel();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.