一个简单的带图标的Toast

《一个简单的带图标的Toast》

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

《一个简单的带图标的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("啦啦啦");

源码点击查看

    原文作者:Vonelone
    原文地址: https://www.jianshu.com/p/71205d02dfc5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞