import android.app.Activity;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* creator gonghaohao
* class name:ToastUtil
* created at 2017/10/16 16:32
* function describe:自定义toast弹框
* 位置居中,包含图片、文字,自定义背景
* modify
*/
public class ToastUtil {
public static void centerToast(final Activity context, String string) {
RelativeLayout layout = (RelativeLayout) context.getLayoutInflater().inflate(R.layout.layout_custom_toast, null);
(layout.findViewById(R.id.tvCheckoutWay)).setBackgroundDrawable(context.getResources().getDrawable(R.mipmap.ic_launcher));
((TextView) layout.findViewById(R.id.tvPercent)).setText(string);
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);//居中
toast.setView(layout);//setting the view of custom toast layout
toast.show();
}
public static void centerPicToast(final Activity context, String string,int pic) {
RelativeLayout layout = (RelativeLayout) context.getLayoutInflater().inflate(R.layout.layout_custom_toast, null);
(layout.findViewById(R.id.tvCheckoutWay)).setBackgroundDrawable(context.getResources().getDrawable(pic));
((TextView) layout.findViewById(R.id.tvPercent)).setText(string);
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(layout);//setting the view of custom toast layout
toast.show();
}
}
布局文件:layout_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="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0.5"
android:background="@drawable/toast_bg">
<ImageView
android:id="@+id/tvCheckoutWay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="@mipmap/ic_launcher"></ImageView>
<TextView
android:id="@+id/tvPercent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvCheckoutWay"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="输入有误"
android:textColor="#aabbcc"
android:textSize="20sp" />
</RelativeLayout>
</RelativeLayout>
toast背景资源文件:toast_bg
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="8dp"></corners>
<solid android:color="#000000"></solid>
</shape>
使用:ToastUtil.centerToast(MainActivity.this, "我是自定义toast");
ToastUtil.centerPicToast(MainActivity.this, "我是自定义toast",R.mipmap.ic_launcher);
效果图