Android实现自定义Toast,并且防止重复显示

来源:互联网 发布:银行家算法 0 4 2 0 编辑:程序博客网 时间:2024/05/29 08:24

此项目地址:https://github.com/chenglin198751/BaseMyProject

这个项目里有个文件就是源码:https://github.com/chenglin198751/BaseMyProject/blob/master/app/src/main/java/widget/MyToast.java


我们在用系统的Toast的时候,总是会发现连续多次点击按钮,就会一直不停的弹,完全停不下来的节奏。那能不能无论点击多少次,就只弹一次呢?

而且我们还想自己定义Toast样式,系统默认样式太难看了。

我就看了下Toast的源码,源码很简单,大概看了十来分钟,就知道了如何自定义。下面贴的是自定义的代码,代码很简单:

/** * Created by chenglin on 2017-7-24. */public class MyToast {    private static Toast mToast;    public static void show(String text) {        TextView msgTv = null;        if (mToast == null) {            mToast = new Toast(MyApplication.getApp());            View view = View.inflate(MyApplication.getApp(), R.layout.my_toast_layout, null);            msgTv = (TextView) view.findViewById(R.id.message);            msgTv.setText(text);            mToast.setView(view);            mToast.setDuration(Toast.LENGTH_SHORT);        } else {            msgTv = (TextView) mToast.getView().findViewById(R.id.message);            msgTv.setText(text);        }        mToast.show();    }}
其中的布局文件你可以自己随意的写,我上面用到的布局文件代码:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/toast_bg"    android:orientation="vertical">    <TextView        android:id="@+id/message"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginBottom="8dp"        android:layout_marginLeft="16dp"        android:layout_marginRight="16dp"        android:layout_marginTop="8dp"        android:gravity="center"        android:textColor="@color/text_color_white"        android:textSize="15dp"        tools:text="我是自定义Toast" /></LinearLayout>

其中的@drawable/toast_bg 的代码如下:
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <corners android:radius="4dp" />    <solid android:color="#82000000" /></shape>

如果你觉得帮到了你,请给作者打赏一口饭吃:




原创粉丝点击