Bamboy的自定义吐司,(以下称作“BToast”)
特点在于使用简单,并且自带两种样式:
1)普通的文字样式;
2)带图标样式。
其中图标有√和×两种图标。
BToast还有另外一个特点就是:
系统自带面包采用的是队列的方式,当前烤消失后,下一个面包才能显示出来。
而BToast会把当前面包顶掉,直接显示最新的吐司。
那么,简单三步,我们现在就开始自定义一下吧!
(一),布局:
要自定义吐司,
首先我们需要一个XML布局。
但是在布局之前我们需要三个资源文件,分别是背景,√和×。
背景可以用XML画出来:
toast_back.xml
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt;形状xmlns: android=" http://schemas.android.com/apk/res/android "比; & lt;角落android:=" 12 dp/半径比; & lt;固体android:颜色=" # CC000000”/比; & lt;/shape> >之前√和×就最好用图片啦,源码里面有这两张图片,这里就不贴出来了。
现在就可以写布局了:
toast_layout.xml
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:背景=" @drawable/toast_back” android:重力=" center_vertical " android:填充=" 13 dp " 面向android:=按怪薄北? & lt; ImageView android: id=癅 + id/toast_img” android: layout_width=" 50 dp” android: layout_height=" 50 dp” android:背景=" @drawable/toast_y” android: layout_gravity=" center_horizontal " android: layout_marginBottom=" 5 dp/比; & lt; TextView android: id=癅 + id/toast_text” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android: layout_gravity=" center_horizontal " android: layout_marginLeft=" 10 dp” android: layout_marginRight=" 10 dp” android:输入textColor=" # FFFFFF " android:重力="中心" android: textSize=" 17 sp "/比; & lt;/LinearLayout> >之前所需要的XML现在已经好了,剩下的就是Java部分了。
(二),Java:
写一个BToast类,继承吐司,成员变量自身单例,还有构造函数:
公开课BToast延伸吐司{/* * *为单例 */私有静态BToast烤面包;/* * *构造 * * @param上下文 */公共BToast(上下文语境){ 超级(上下文); } } >之前为了实现可以吧当前面包顶下去的需求,我们需要重写几个方法
/* * *隐藏当前面包 */公共静态孔隙cancelToast () { 如果(吐司!=null) { toast.cancel (); } } 公共空间取消(){ 尝试{ super.cancel (); }捕捉(异常e) { } } @Override 公共空间展示(){ 尝试{ super.show (); }捕捉(异常e) { } } >之前现在我们就可以写我们的逻辑了,首先当然是引入我们的布局咯:
/* * *初始化吐司 * * @param上下文上下文 * @param文本显示的文本 */私有静态孔隙initToast(上下文语境,CharSequence进行文本){ 尝试{ cancelToast (); 烤面包=new BToast(上下文);//获取LayoutInflater对象 LayoutInflater增压泵=(LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);//由布局文件创建一个视图对象 视图布局=inflater.inflate(出来。toast_layout, null);//吐司上的图片 toast_img=(ImageView) layout.findViewById (R.id.toast_img);//吐司上的文字 TextView toast_text=(TextView) layout.findViewById (R.id.toast_text); toast_text.setText(文本); toast.setView(布局); toast.setGravity(重力。中心,0,70); }捕捉(异常e) { e.printStackTrace (); } } >之前超简单实现Android自定义吐司示例(附源码)