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

此项目地址: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>

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




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值