public class ToastUtils {
private static Toast toast;
/**
*
* @param context
* @param resource 图标
* @param text 内容
* @param width toast宽
* @param height toast高
*/
public static void show(Context context, int resource, String text, int width, int height) {
if(toast == null) {
synchronized (ToastUtils.class) {
if(toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
}
}
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.toast, null);
LinearLayout layout = view.findViewById(R.id.toastLayout);
int w = dp2px(context, width);
int h = dp2px(context, height);
ViewGroup.LayoutParams layoutParams = layout.getLayoutParams();
layoutParams.height = h;
layoutParams.width = w;
layout.setLayoutParams(layoutParams);
((TextView) view.findViewById(R.id.text)).setText(text);
((ImageView) view.findViewById(R.id.icon)).setImageResource(resource);
toast.setView(view);
toast.setGravity(Gravity.BOTTOM, 0, PlatesUtils.dp2px(context, 30));
toast.show();
}
public int dp2px(Context context, float dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
<LinearLayout
android:id="@+id/toastLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_toast"
android:gravity="center"
android:padding="0dp"
android:layout_margin="0dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="30dp"
android:layout_height="30dp"/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="33sp"
android:textColor="@color/white"
android:maxLines="1"/>
</LinearLayout>
</LinearLayout>