本文将介绍toast的三种使用方式及如何修改toast显示时长
- 默认的toast
- 改变位置的toast
- 带图片的toast
运行效果:
1、默认的toast
Toast.makeText(EasyDemoActivity.this,"我是默认的toast",Toast.LENGTH_SHORT).show();
2、改变位置的toast
改变位置的toast设置步骤
- 声明一个toast
- toast设置位置,xOffetset,yOffetset:偏移量
- 将toast显示
//改变位置的toast设置步骤
//1、声明一个toast
//2、toast设置位置,xOffetset,yOffetset:偏移量
//3、将toast显示
Toast toast=Toast.makeText(EasyDemoActivity.this,"我是改变位置的toast",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
3、带图片的toast
实现思路:将layout放于inflate中,对layout中的控件设置内容(图片/文字),将inflate设置到toast中
需要新建一个布局用于设置我们自定义的toast:
注意!!此处item布局中对根布局设置的宽高是不起效果的,一定要在根布局中嵌套一个布局!
<?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="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<ImageView
android:id="@+id/iv_cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="@mipmap/picture" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
Toast toastImage=new Toast(this);
LayoutInflater inflater=LayoutInflater.from(this);
View inflateView = inflater.inflate(R.layout.layout_toast, null);
ImageView imageView=inflateView.findViewById(R.id.iv_cover);
TextView textView=inflateView.findViewById(R.id.tv_title);
imageView.setImageResource(R.mipmap.picture);
textView.setText("我是带图片的toast");
toastImage.setView(inflateView);
toastImage.show();
toast多次点击设置显示时长
一般我们在使用toast的时候会出现该问题:多次点击toast会一直跳出多个toast,显示的时间就会很长,而我们预期的效果确实多次点击只跳出最后一个toast!
解决方案:
创建一个工具类将toast进行包装
public class ToastUtils {
public static Toast mToast;
public static void showMsg(Context context, String msg) {
if (mToast == null) {
mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
} else {
mToast.setText(msg);
}
mToast.show();
}
}
再使用该方法即可达到我们要的效果:
ToastUtils.showMsg(EasyDemoActivity.this,"我是默认的toast");