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

本文介绍了一个自定义ToastManager类来解决在EditText中输入超过限制字数时,Toast长时间不消失的问题。通过全局使用一个Toast实例,确保Toast在短时间内的正常显示与消失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     最近我在项目中自定义了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

<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/toast_frame" android:orientation="vertical"><TextView android:id="@android:id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_weight="1" android:fontFamily="sans-serif-condensed" android:shadowColor="#BB000000" android:shadowRadius="2.75" android:textColor="@android:color/background_light"/></LinearLayout>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值