1. 默认创建
Toast是一种简易的消息提示框,toast提示框不能被用户点击,会根据用户设置的显示时间后自动消失。Toast静态方法makeText(),生成Toast实例,并调用show()方法来显示。
Toast.makeText(Context context, CharSequence text, int duration)
Toast.makeText(Context context, int resId, int duration)
duration可以选择Toast.LENGTH_SHORT或Toast.LENGTH_LONG。
2. 设置显示位置
调用setGravity()来设置Toast最终显示的位置,gravity使用android.view.Gravity中参数。
setGravity(int gravity, int xOffset, int yOffset)
假如我们设置一个居中显示的Toast。
Toast toast = Toast.makeText(this, "自定义位置Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
效果如下
3. 创建自定义Toast
调用setView(View)来添加自定义的Toast。
Toast toast = new Toast(this);
toast.setView(getLayoutInflater().inflate(R.layout.toast_custom_view, null));
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
布局文件toast_custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="5dp"
android:background="#ffa6a5aa">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast标题"
android:textColor="#ffffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toast消息内容"
android:textColor="#ffffffff"/>
</LinearLayout>
</LinearLayout>
效果如下
4. 取消显示
Toast会显示一段时间后消失,如果等不及的话可以调用cancel()方法取消显示。
相关文章
Android Toast类
Android PopupWindow类
Android AlertDialog类