概述
一个 toast 是在屏幕上弹出一条信息,它的大小总是包裹着需要显示的内容,并且当前的 Activity 依然是可见并且可互动的。toast会自动消失,并且不接受任何互动事件。因为 toast 可以在后台的 Service
中创建,所以即使这个应用程序没有显示在屏幕上,仍然可以弹出 toast.
toast 最好用来显示简要的信息,比如断定用户正在注意屏幕时,弹出"File saved". toast 不能接受任何用户互动事件,如果需要用户响应并采取操作,考虑使用 状态栏通知 来替代.。
基本使用
Toast.makeText(ToastActivity.this, "默认提示", Toast.LENGTH_SHORT).show();
指定显示位置
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
追加图片
LinearLayout linearLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(ToastActivity.this);
imageView.setImageResource(R.mipmap.ic_launcher);
linearLayout.addView(imageView);
自定义布局
View view1 = LayoutInflater.from(ToastActivity.this).inflate(R.layout.layout_toast, null);
toast.setView(view1);
<?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:src="@drawable/qq_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show_text"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
在线程中使用
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast = Toast.makeText(ToastActivity.this, "线程中提示", Toast.LENGTH_SHORT);
toast.show();
}
});
控制显示时间:
public static void showMyToast(final Toast toast, final int cnt)
{final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
toast.show();
}}, 0, 3000);
new Timer().schedule(new TimerTask()
{@Override
public void run() {
toast.cancel();
timer.cancel(); } }, cnt );}
public static void show(Context context, String info) {
try {
Toast toast=Toast.makeText(context,info, Toast.LENGTH_LONG);
showMyToast(toast, 1000); }
catch (Exception e){ }}