一个简单的带图标的Toast

作者: Vonelone | 来源:发表于2017-06-19 18:07 被阅读264次

这次把自定义的魔爪伸向了Toast。效果就是下面这样


废话不多说,直接上代码

public class ToastUtil {
    private Context context;
    private Toast toast;

    public ToastUtil(Context context) {
        this.context = context.getApplicationContext();
        toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
    }

    public boolean showToast(String str) {
        if (toast.getView().getParent() != null) {
            if (toast.getView().getContentDescription().equals(str)) {
                return false;
            } else {
                toast.cancel();
                toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
                toast.show();
            }
        } else {
            toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
            toast.show();
        }
        return true;
    }

    public boolean showToastWithImg(String str, Drawable imgRes) {
        if (toast.getView().getParent() != null) {
            toast.cancel();
        }
        toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);

        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(16);
        textView.setText(str);
        textView.setPadding(80, 0, 80, 0);
        imgRes.setBounds(0, 0, imgRes.getMinimumWidth(), imgRes.getMinimumHeight());
        textView.setCompoundDrawables(imgRes, null, null, null);
        textView.setBackground(context.getResources().getDrawable(R.drawable.shape_round_toast));

        toast.setView(textView);

        toast.show();


        return false;
    }
}

原理就是在<code>toast.setView()</code>这里,简单粗暴。

把toast里的View替换为TextView,Textview就随便我们玩了,设置图标和背景手到擒来,甚至可以用自定义的view。。

本例就是写一个简单的shape作为textView的bg,或者用逼格高一点的图片都行。随性着来

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="50dp"/>
    <solid android:color="@color/colorPrimary_alpha"/>
    <corners android:radius="100dp"/>
</shape>

代码中使用

先实例化工具类

toastUtil = new ToastUtil(getApplicationContext());

在需要吐司的地方调用写好的方法

带图标的

toastUtil.showToastWithImg("读取系统信息",
            getResources().getDrawable(R.drawable.ic_device_info_toast));

不带图标的

toastUtil.showToast("啦啦啦");

源码点击查看

相关文章

网友评论

  • 6d1ed8cfdd1c:快速多次点击时 toast.getView().getContentDescription().equals(str) 报空指针 导致崩溃。。。
    Vonelone:感谢指出 , 这里设计冗余了 , 原方法改成这样就行了:
    public boolean showToast(String str) {
    if (toast.getView().getParent() != null) {
    toast.cancel();
    }
    toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
    toast.show();
    return true;
    }
  • 厂里的帅小伙:简明扼要
  • HalouFeng:请问下,为什么要判断toast.getView().getParent()是否为空呢
    Vonelone:@China丰 就是判断当前有上一条toast正在显示时,把它cancel掉,再显示本条。这个是解决快速多次点击,导致的toast排队显示影响流畅性的问题。。
  • 雅虎通:不孬不孬:clap:
    Vonelone:多谢夸奖:wink:

本文标题:一个简单的带图标的Toast

本文链接:https://www.haomeiwen.com/subject/hjcnqxtx.html