package com.example.test;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ToastUtil {
//显示文本+图片的Toast
public static void showImageToas(Context context, String message) {
View toastview = LayoutInflater.from(context).inflate(R.layout.toast_style, null);
TextView text = toastview.findViewById(R.id.tv);
text.setText(message); //要提示的文本
Toast toast = new Toast(context); //上下文
toast.setGravity(Gravity.CENTER, 0, 0); //位置居中
toast.setDuration(Toast.LENGTH_SHORT); //设置短暂提示
toast.setView(toastview); //把定义好的View布局设置到Toast里面
toast.show();
}
//显示文本的Toast
public static void showTextToas(Context context, String message) {
View toastview = LayoutInflater.from(context).inflate(R.layout.toast_style2, null);
TextView text = toastview.findViewById(R.id.tv);
text.setText(message);
Toast toast = new Toast(context);
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastview);
toast.show();
}
}
<?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:background="@color/colorPrimaryDark"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#fff" />
</LinearLayout>
引用:
ToastUtil.showImageToas(this, "我是Toast");
//ToastUtil.showTextToas(this, "我是Toast");