前几天写了一个自定义Toast,加入了图标,文字,多次点击不会重复显示等功能。
显示效果如图所示:
下面开始贴代码:
java代码
public class ToastCancel {
public static ToastCancel toastCancel;
private static View view;
private static Toast toast;
private static TextView text;
private static ImageView img;
private ToastCancel() {
}
public static ToastCancel getInstance(Context context) {
if (toast == null) {
toastCancel = new ToastCancel();
view = LayoutInflater.from(context).inflate(R.layout.toast_cancel, null);
text = (TextView) view.findViewById(R.id.text_toast);
img = (ImageView) view.findViewById(R.id.img_toast);
toast = new Toast(context);
toast.setGravity(Gravity.CENTER, 0, 0); // Toast显示的位置
toast.setDuration(Toast.LENGTH_SHORT); // Toast显示的时间
toast.setView(view); // 设置Toast布局
}
return toastCancel;
}
/**
* 显示
*/
public void show(int drawable, String str) {
text.setText(str); // 设置显示文字
img.setImageResource(drawable);//设置显示图标
toast.show();
}
public void cancel() {
if (toast != null) {
toast.cancel();
}
}
}
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/toast_emailOne_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast_bg"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="4dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:paddingTop="4dp">
<ImageView
android:id="@+id/img_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/offline" />
<TextView
android:id="@+id/text_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="网络异常,请检查网络环境"
android:textColor="#ffffff"
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
drawable文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#77000000"></solid>
<corners android:radius="20dp"></corners>
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp"></padding>
</shape>
调用方式
ToastCancel.getInstance(MainActivity.this).show(R.mipmap.file, "我是自定义Toast");