自定义Toast、避免连续点击,持续弹出问题

一、避免连续点击后,Toast持续弹出,体验不好

public class ToastUtil  {
    private static Context context = null;
    private static Toast toast = null;
    public static void getToast(Context context,String theText){
        if (toast == null) {
            toast = Toast.makeText(context, theText, Toast.LENGTH_SHORT);
        } else {
            toast.setText(retId);
            toast.setDuration(Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}

使用:Toast.getToast(MainActivity.this,"我的Toast");

到此就完成了

二、自定义样式的Toast

public class CustomerToast {

    private static Toast toast;

    public static void showToast(Context context, String content) {

        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.toast_show, null);
        TextView tv = (TextView) view.findViewById(R.id.tv_toast_text);
        tv.setText(content);

        //防止多次点击按钮出现很多toast一直不消失
        if (toast != null) {
            toast.setView(view);
        } else {
            toast = new Toast(context);
            toast.setView(view);
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
        }
        toast.show();
    }
}

下面是布局文件toast_show

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/mytoastshape"
        android:gravity="center"
        android:paddingBottom="8dp"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:paddingTop="8dp"
        android:textColor="#ffffff" />
</LinearLayout>

在drawable文件夹下创建Toast样式:mytoastshape

<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/darker_gray" />
    <corners android:radius="16dp" />
</shape >

使用:

CustomerToast.showToast(MainActivity.this, "我的Toast");

完成

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值