1. 程式人生 > >自定義View繼承現有的Toast,實現訂單提醒的Toast,從左下角顯示然後退出

自定義View繼承現有的Toast,實現訂單提醒的Toast,從左下角顯示然後退出

自定義View繼承現有的Toast,實現訂單提醒的Toast,從左下角顯示然後退出





/**
 * Created by  on 16-2-4.
 */
public class NotifyToast extends Toast {
    private long lastShowTime;
    public static NotifyToast instance;
    public static synchronized NotifyToast getInstance(Context context){
        if(instance==null){
            instance = new NotifyToast(context,"你有未處理的訂單,請抓緊處理",3000);
        }
        return instance;
    }

    private MediaPlayer mPlayer;
    /**
     * Construct an empty Toast object.  You must call {@link #setView} before you
     * can call {@link #show}.
     *
     * @param context The context to use.  Usually your {@link Application}
     *                or {@link Activity} object.
     */
    public NotifyToast(Context context,CharSequence text, int duration) {
        super(context);
        mPlayer = MediaPlayer.create(context, R.raw.neworder);
        //2016年08月02日10:51:32 不需要設定完成後釋放資源的回撥,整段註釋掉了
//        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
//        {
//            @Override
//            public void onCompletion(MediaPlayer mp)
//            {
////                mp.release();// 釋放資源。讓資源得到釋放;;
//            }
//        });

        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        View v = inflate.inflate(R.layout.new_data_toast, null);
        // v.setMinimumWidth(dm.widthPixels);// 設定控制元件最小寬度為手機螢幕寬度
        setView(v);
        this.setDuration(duration);// 設定 顯示多長時間;;;;
        this.setGravity(Gravity.LEFT|Gravity.BOTTOM, (int) (dm.density * 10), (int) (dm.density * 10));

    }

    public void show() {
        long nowTime = new Date().getTime();
        if (nowTime - lastShowTime > 10000) {
            super.show();
            if(mPlayer!=null) {
                mPlayer.start();
            }
            lastShowTime = nowTime;
        }
    }
}