Android中的Toast是一种简易的消息提示框。
当视图显示给用户,在应用程序中显示为浮动。和Dialog不一样的是,它永远不会获得焦点,无法被点击。用户将可能是在中间键入别的东西。Toast类的思想就是尽可能不引人注意,同时还向用户显示信息,希望他们看到。而且Toast显示的时间有限,Toast会根据用户设置的显示时间后自动消失。
Toast的使用
最简单的使用方式,makeText设置内容和显示时间。
调用show方法显示
Toast.makeText(getApplicationContext(), "默认Toast样式",
Toast.LENGTH_SHORT).show();
当然可以设置其他属性
比如:
显示位置
Toast toast = Toast.makeText(getApplicationContext(),
"自定义位置Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
显示图片+文字
给Toast添加View ,Toast有个addView方法,可以加入View.
具体步骤如下:
- 使用getView获取Toast的布局
- 新建View
- addView()
toast = Toast.makeText(getApplicationContext(),
"带图片的Toast", Toast.LENGTH_LONG);
//设置位置
toast.setGravity(Gravity.CENTER, 0, 0);
//给Toast添加view
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView imageCodeProject = new ImageView(getApplicationContext());
imageCodeProject.setImageResource(R.mipmap.ic_launcher);
//添加
toastView.addView(imageCodeProject, 0);
toast.show();
完全自定义样式
其实可以不用系统的方法,直接全部自定义:
定义布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/llToast"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tvTitleToast"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/tvImageToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvTextToast"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
使用布局文件:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom,
(ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout
.findViewById(R.id.tvImageToast);
image.setImageResource(R.mipmap.ic_launcher);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("完全自定义Toast");
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
测试:
参考文章:这里写链接内容