Android中系统自带的Toast都是白色字体,黑色背景的,这样子用久了总感觉不好看,要是想自己定义Toast,怎么办?废话少说,直接看Toast的源码,如下:
public static Toast makeText(Context context, CharSequence text, @Duration int duration) { Toast result = new Toast(context); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null); TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message); tv.setText(text); result.mNextView = v; result.mDuration = duration; return result; }平时我们Toast.makeText(context,"自定义toast",Toast.LENGTH.LONG).show();都是调用这段代码的,可以看到里面有一个布局文件
R.layout.transient_notification
让我们一起去看下这个布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="?android:attr/toastFrameBackground"> <TextView android:id="@android:id/message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_horizontal" android:textAppearance="@style/TextAppearance.Toast" android:textColor="@color/bright_foreground_dark" android:shadowColor="#BB000000" android:shadowRadius="2.75" /> </LinearLayout>很简单,只有这么一点,就是一个TextView,我们的吐司提示字体颜色由textColor决定,我们的背景由布局的background决定,所以,你要想得到怎么样的自定义Toast,可以直接在这里改变源码,哈哈,当然这种方式不好,最好还是自己写一个工具类来修改,我自己也写了一个ToastUtil工具类,可以修改Toast的字体颜色,整体背景,局部背景,自定义布局等等,下面给出代码可以下载,要是有自己其他需求可以自己添加。
ToastUtil工具类地址:点击打开链接