如何在Android自定义Toast

为啥要自定义Toast


欢迎大家访问我的Github开源库,这里有好玩的App源码,想和大家分享。https://github.com/ChoicesWang

当时我也不明白,直接用系统默认的Toast不就行了吗 。后来我们产品说,默认Toast长的太丑,和我们的产品的逼格不一致。其实自定义Toast很简单。但是好多人都不知道,我这里做了一个简单的样式,方便大家参考。如果你需要更牛逼的Toast,那就需要查阅资料,自己写了。

不过。你也可以在Github中搜索 android toast 关键词,按最多点赞的排序,一下就会发现很多牛逼的优秀的开源项目。

https://github.com/search?o=desc&q=Android+Toast&s=stars&type=Repositories&utf8=%E2%9C%93

哎,大招都告诉你们了,我还写什么博客啊。

原创地址:http://blog.csdn.net/zezeviyao/article/details/46724587

来来来,看看我的Toast

产品说需要这样一个Toast。在通知栏下方,左右占满整个屏幕,上下46dp。等会,我截个效果图给你们看。
这里写图片描述

大致就是这样的吧

接下来看看代码吧:

//自定义Toast
public class Ftoast {

    private Context mContext; //上下文
    private TextView txtContent; //文本内容
    private Toast toast; //原始Toast

    //注意,这里是private,意思就是不让你自己new。
    private Ftoast(Context context) {
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //加载自定义的XML布局
        View root = inflate.inflate(R.layout.toast, null);
        txtContent = (TextView) root.findViewById(R.id.txtToast);
        toast = new Toast(context);
        toast.setView(root); //这是setView。就是你的自定义View
        //这是,放着顶部,然后水平放满屏幕
        toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
    }

    //这是个简易工厂模式
    public static Ftoast create(Context context) {
        Ftoast ft = new Ftoast(context);
        ft.toast.setDuration(Toast.LENGTH_SHORT);
        return ft;
    }
    // 文字 (然而这并没有什么卵用)
    public Ftoast setText(String text) {
        this.txtContent.setText(text);
        return this;
    }
    // Duration。这是Toast.LENGTH_SHORT 或者 Toast.LENGTH_LONG
    // 别瞎写什么 1000 、2000。真是醉了。
    public Ftoast setDuration(int duration) {
        this.toast.setDuration(duration);
        return this;
    }
    // 注意,必须要调用show。不然写Toast干嘛。
    public void show() {
        this.toast.show();
    }
}

来来来,在看看超级简单的XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#CC33CA">

    <TextView
        android:id="@+id/txtToast"
        android:layout_width="match_parent"
        android:layout_height="46dp"
        android:layout_centerInParent="true"
        android:ellipsize="end"
        android:gravity="center"
        android:singleLine="true"
        android:textColor="#FFFFFF"
        android:textSize="16sp" />

</RelativeLayout>

来来来,说说怎么用吧

Ftoast.create(getActivity()).setText("然而这并没有什么卵用").show();

或者

Ftoast.create(getActivity()).setText("然而这并没有什么卵用").setDuration(Toast.LENGTH_LONG).show();

默认是Short。短的 。写的时候就想第一种。
原创地址:http://blog.csdn.net/zezeviyao/article/details/46724587

如果您有好的工作机会,请联系我:
王建磊
zezeviyao@163.com

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值