Toast是一种轻量级提示工具,而且提示并不会聚焦,所以并不会影响用户的操作,在Toast上一个层级的activity依旧会是Resume状态,并不会进入Pause。
通常我们只是使用Toast的默认布局和纯文字显示,但是Toast是可以根据我们的需求进行功能自适应调整的。
1.默认Toast
//显示的上下文、内容、时间
Toast toast=Toast.makeText(context,text,duration);
//显示
toast.show();
视图:
2.Toast位置可调整
//显示的上下文、内容、时间
Toast toast=Toast.makeText(context,text,duration);
//设置位置、x轴偏移量、y轴偏移量
toast.setGravity(Gravity.TOP, int xOffset, int yOffset);
//显示
toast.show();
视图:
3.包含图片的Toast
//显示的上下文、内容、时间
Toast toast=Toast.makeText(context,text,duration);
//利用getView获得View对象,并强制转化为linearlayout
LinearLayout ll=(LinearLayout)toast.getView();
//创建一个ImageView对象,并且设置图片
ImageVIew iv=new ImageView(this);
iv.setImageResource(R.mipmap.ic_launcher);
//将image添加进toast的布局中
ll.addView(iv);
//显示
toast.show();
视图:
4.自定义Toast
因为自定义Toast需要借助xml文件来布局我们的显示效果,所以该内容还会贴出xml布局文件
layout文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是自定义TOast"/>
</LinearLayout>
java源代码:
//创建一个Toast对象
Toast toast=new Toast(this);
返回一个填充了自定义布局的view
View view = LayoutInflater.from(this).inflate(R.layout.sublist,null);
//将view添加到Toast中
toast.setView(view);
//显示Toast
toast.show();
视图: