连续弹出的多个Toast长时间显示,不消失。

     最近我在项目中自定义了Edittext,当字数到达限定值的时候,将弹Toast提示字数超限。在字数达到限定值后,再连续的输入,Toast会长时间显示不消失。通过查看源码,每次Toast.makeText(context, message, Toast.LENGTH_SHORT).show()时候,都会new一个Toast并把它加入到消息队列中排队显示,造成Toast长时间不消失,影响用户体验。

    解决方案:定义ToastManager,全局使用一个Toast,这样Toast会正常消失。代码如下:

public class ToastManager {

    private Toast mToast;// 如果定义成静态的变量,会造成内存泄露。

    public ToastManager(Context context) {
        mToast = new Toast(context.getApplicationContext());

        LayoutInflater inflate = (LayoutInflater)
                context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.toast, null);

        mToast.setView(v);
        mToast.setDuration(Toast.LENGTH_SHORT);
    }

    /**
     * @param message Toast的信息
     */
    public void showToast(String message) {
        if (null != mToast) {
            mToast.setText(message);
            mToast.show();
        }
    }

    /**
     * @param stringId Toast信息的id
     */
    public void showToast(int stringId) {
        if (null != mToast) {
            mToast.setText(NoteAppImpl.getContext().getResources().getString(stringId));
            mToast.show();
        }
    }

    public void destroy() {
        mToast = null;
    }
}


toast.xml


你可能感兴趣的:(连续弹出的多个Toast长时间显示,不消失。)