自定义一个Toast工具类
该类通过自定义View的形式,去自定义toast 的风格样式,在其他地方直接调用showShortToast等静态方法即可
public class ToastUtil {
private static Toast toast;
private static View view;
private static TextView mMsgText;
private ToastUtil() {
}
@SuppressLint("ShowToast")
private static void getToast(Context context) {
if (toast == null) {
toast = new Toast(context);
toast.setGravity(Gravity.BOTTOM, 0, ScreenUtil.dip2px(50));
}
if (view == null || mMsgText == null) {
view = LayoutInflater.from(context).inflate(R.layout.custom_toast,null);
mMsgText = (TextView)view.findViewById(R.id.toast_msg);
}
toast.setView(view);
}
public static void showShortToast( CharSequence msg) {
showToast(BaseApplication.getAppContext(), msg, Toast.LENGTH_SHORT);
}
public static void showShortToast( int resId) {
showToast(BaseApplication.getAppContext(), resId, Toast.LENGTH_SHORT);
}
public static void showLongToast(CharSequence msg) {
showToast(BaseApplication.getAppContext(), msg, Toast.LENGTH_LONG);
}
public static void showLongToast( int resId) {
showToast(BaseApplication.getAppContext(), resId, Toast.LENGTH_LONG);
}
private static void showToast(Context context, CharSequence msg,
int duration) {
try {
getToast(context);
mMsgText.setText(msg);
toast.setDuration(duration);
toast.show();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void showToast(Context context, int resId, int duration) {
try {
if (resId == 0) {
return;
}
getToast(context);
mMsgText.setText(resId);
toast.setDuration(duration);
toast.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
用到的xml 文件 custom_toast
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_toast_bg_5"
android:layout_margin="5dp"
android:elevation="2dp"
android:gravity="center"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingEnd="27dp"
android:paddingStart="27dp"
android:paddingTop="8dp">
<TextView
android:id="@+id/toast_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:text="@string/app_name"
android:textColor="@color/white"
android:textSize="12dp" />
</LinearLayout>
</RelativeLayout>
实现的效果图