首先给toast一个布局view
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:background="#0a0084FD"> <TextView android:id="@+id/toastText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:textColor="@color/colorPrimaryDark" android:textSize="16sp" /> </FrameLayout>toast正文代码部分,创建一个自己的toast类
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.Toast; import honghu.com.hong_hu.R; /** * Created by Administrator on 2017/5/12. */ public class MyToast { private Toast mToast; /** * @param context 一个上下文对象 * @param text toast的文本内容 * @param duration toast的时间显示 * 在构造方法中将自定义toast进行初始化 */ public MyToast(Context context, CharSequence text, int duration) { View view = LayoutInflater.from(context).inflate(R.layout.mytoast_view, null); TextView toastText = (TextView) view.findViewById(R.id.toastText); mToast = new Toast(context); toastText.setText(text); mToast.setDuration(duration); mToast.setView(view); } public static MyToast makeText(Context context, CharSequence text, int duration) { return new MyToast(context, text, duration); } public void show() { if (mToast != null) { mToast.show(); } } public void setGravity(int gravity, int xOffset, int yOffset) { mToast.setGravity(gravity, xOffset, yOffset); } }