一、简介
toast是我们在网络请求失败或是用户信息填写不正确时用于提示的一种轻量级反馈。我们可以通过
Toast.makeText(this, "这是一条Toast", Toast.LENGTH_SHORT).show();
来弹出一条toast。效果如下图:
但是有些时候,当我们需要改变toast的样式时,android自带的toast显然不能满足我们的要求,如居中显示。所以这时候,我们就需要自定义toast。
二、实现过程
下面我来介绍一下如何实现一个居中显示的圆形toast(其他样式的toast实现原理相同)
1.自定义布局
toast_rounded.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_rounded_toast">
<TextView
android:id="@+id/tv_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="10dp"
android:textSize="12sp"
android:textColor="@color/white" />
</RelativeLayout>
这就是我们具体展现的toast的样式,我只在布局里添加了一个TextView用于文字的展示,我们还可以添加ImageView或者其他我们想要的控件实现不同的样式效果。圆角的样式我们使用drawable实现,然后设置为我们布局的背景。
shape_rounded_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="44dp" />
<solid android:color="@color/color_99000000" />
</shape>
corners是圆角的角度。
2.toast类
/**
* 圆角Toast
*
* ljy545733599@163.com
*/
public class RoundedToast {
/**
* 展示toast==LENGTH_SHORT
*
* @param msg
*/
public static void show(Context context, String msg) {
show(context, msg, Toast.LENGTH_SHORT);
}
/**
* 展示toast==LENGTH_LONG
*
* @param msg
*/
public static void showLong(Context context, String msg) {
show(context, msg, Toast.LENGTH_LONG);
}
private static void show(Context context, String massage, int show_length) {
if (context == null) {
return;
}
//使用布局加载器,将编写的toast_layout布局加载进来
View view = LayoutInflater.from(context).inflate(R.layout.toast_rounded, null);
//获取TextView
TextView title = view.findViewById(R.id.tv_toast);
//设置显示的内容
title.setText(massage);
Toast toast = new Toast(context);
//设置Toast要显示的位置,水平居中并在底部,X轴偏移0个单位,Y轴偏移70个单位,
toast.setGravity(Gravity.CENTER, 0, 0);
//设置显示时间
toast.setDuration(show_length);
toast.setView(view);
toast.show();
}
}
我们通过LayoutInflater将我们定义好的toast布局加载进来,获取其中的TextView设置我们要展示的文字。
然后初始化一个Toast对象,通过setGravity方法设置toast居中,并setView设置布局View,最后通过show方法显示。
3.具体使用
RoundedToast.show(this,"这是一条Toast");