1. 程式人生 > >android 自定義toast停留時間

android 自定義toast停留時間

Toast類

    //首先定義全域性變數mToast已經顯示和隱藏函式
    private Toast mToast;
    // 隱藏toast資訊框常量
    public static final int AIRPLAY_MESSAGE_HIDE_TOAST = 22;
    // 顯示toast資訊框時間
    public static final int AIRPLAY_TOAST_DISPLAY_TIME = 1000;

    public void showShortToast(String text) {
        if(mToast == null) {
            mToast = Toast.makeText(AppContext.getInstance(), text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

呼叫

final Handler m_Handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        // TODO Auto-generated method stub
                        switch (msg.what) {
                            case 0:
                                break;
                            case BaseActivity.AIRPLAY_MESSAGE_HIDE_TOAST: {
                                cancelToast();
                                break;
                            }
                        }
                    }
                };
      showShortToast(getString(R.string.error_tag_name_input));
      Message delayMsg = m_Handler.obtainMessage(AIRPLAY_MESSAGE_HIDE_TOAST);
      m_Handler.sendMessageDelayed(delayMsg, AIRPLAY_TOAST_DISPLAY_TIME);

   private static final int LONG_DELAY = 3500// 3.5 seconds           

   private static final int SHORT_DELAY = 2000// 2 seconds

Toast.Long = 3.5s

Toast.short = 2.0s

Toast..makeText(Context context,CharSequence text, int duration).show() 中的duration只能設這兩個值,其他值是沒有用的