为啥要自定义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