自定义的Toast的实现,总的来说就是先对自己的Toast的布局效果xml进行编写,然后,在根据xml对我们自定义的Toast进行自定义的封装方法,然后哪里使用哪里调用就OK啦。
先上效果图:(不输入信息,点击登陆,弹出了自定义的Toast)
然后我们自定义toast的布局,toast.xml:
(此处的Button也可以是ImageView等,Toast的显示看个人需要)
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal"> <Button android:id="@+id/btn_toast" android:layout_width="300dp" android:layout_height="50dp" android:layout_gravity="center_horizontal" android:background="@mipmap/toast" android:textColor="#FFFFFF" android:textSize="15dp" /> </RelativeLayout>
对于自定义Toast的封装类ToastCommon.class
public class ToastCommon { private static ToastCommon toastCommon; private Toast toast; private ToastCommon() { } public static ToastCommon createToastConfig() { if (toastCommon == null) { toastCommon = new ToastCommon(); } return toastCommon; } /** * 显示Toast */ public void ToastShow(Context context, ViewGroup root, String tvString) { View layout = LayoutInflater.from(context).inflate(R.layout.toast, root); Button btn_toast = (Button) layout.findViewById(R.id.btn_toast); btn_toast.setBackgroundResource(R.mipmap.toast); btn_toast.setText(tvString); btn_toast.setTextColor(Color.WHITE); toast = new Toast(context); toast.setGravity(Gravity.CENTER, 0, 400); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); } }
最后就是哪里调用哪里声明调用了。具体如下:
private ToastCommon toastCommon;
toastCommon = ToastCommon.createToastConfig(); toastCommon.ToastShow(LoginActivity.this, (ViewGroup) findViewById(R.id.toast_layout_root), "请输入登陆信息");
先声明我们的类,然后create方法,然后ToastShow方法。就可以啦。