默认Toast
`Toast.makeText(getApplicationContext(),"默认",Toast.LENGTH_LONG).show();
改变位置
Toast toast=Toast.makeText(getApplicationContext(),"居中显示",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
自定义显示内容
//显示的layout文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="200dp"
android:layout_height="200dp"
android:background="#99000000">
<ImageView
android:id="@+id/iv_toast"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitCenter"/>
<TextView
android:id="@+id/tv_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@color/colorPrimary"/>
</LinearLayout>
Toast toast=new Toast(context);
LayoutInflater inflater=LayoutInflater.from(context);
View view=inflater.inflate(R.layout.layout_toast,null);//调用layout文件
ImageView imageView=view.findViewById(R.id.iv_toast);
imageView.setImageResource(R.drawable.iv_mac);//设置显示的图片
TextView textView=view.findViewById(R.id.tv_toast);
textView.setText("显示layout的Toast"); //设置显示的文字
toast.setView(view);//设置view
toast.setDuration(Toast.LENGTH_LONG);//设置显示的时间
toast.setGravity(Gravity.CENTER,0,0);//设置显示的位置
toast.show();
public class ToastUtil {
/**
* Toast实例,用于对本页出现的所有Toast进行处理
*/
private static Toast myToast;
/**
* 此处是一个封装的Toast方法,可以取消掉上一次未完成的,直接进行下一次Toast
*
* @param context context
* @param text 需要toast的内容
*/
public static void toast(Context context, String text) {
if (myToast != null) {
myToast.cancel();
myToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
//myToast.setGravity(Gravity.CENTER, 0, 0);
} else {
myToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
//myToast.setGravity(Gravity.CENTER, 0, 0);
}
myToast.show();
}
}