概述:
Toast是Android用来给予用户操作反馈的一个小弹窗. 它需要所显示的内容的空间大小, 并且和当前的activity保持交互. 比如, 我们在保存一个文本的时候会弹出一个toast显示”保存成功”提示我们可以继续编辑了. Toast会在显示一小段时间之后自动消失. 这是它的样子:
如果用户需要响应这条消息, 那么应该考虑使用Notification.
基本使用方法:
首先通过makeText()方法实例化一个Toast对象. 该方法有三个参数, 分别是APP Context, text message和toast的持续时间. 它返回一个初始化过的toast对象. 然后我们就可以通过show()方法来显示这个toast了. 栗子:
Context context = getApplicationContext();
CharSequence text = "Hellotoast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
这个栗子演示了需要显示一个toast所需的所有信息, 基本上不需要再使用其它的东西了. 然而有时候我们可能想要让toast显示在不同的位置或者想要自定义toast的layout. 下文将会介绍这些操作. 通常我们这样使用一个toast:
Toast.makeText(context, text, duration).show();
定位toast:
默认情况下, toast显示在靠近屏幕底端的位置, 水平居中对齐. 如果想要修改的话我们可以通过setGravity(int, int, int)方法来修改, 该方法接收3个参数: 一个Gravity常数, X方向偏移, Y方向偏移. 比如如果我们需要toast出现在左上角, 我们可以这样设置:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
如果想要往右边微调, 那就增加第二个参数的值, 如果想要往下微调, 就增加第三个参数的值.
创建一个自定义的ToastView:
如果一个简单的文字消息还不能满足我们的需求, 我们可以为我们的toast创建一个自定义的layout. 想要实现这一功能需要创建XML layout文件然后通过setView(View)方法设置. 比如我们可以这样设置一个layout文件(toast_layout.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
/>
</LinearLayout>
这里我们需要为LinearLayout指定ID, 上文的ID是”toast_layout_root”, 在加载该layout的时候需要用到这个ID, 代码如下:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
首先获取到View, 设置内容, 然后通过Toast的setView(View)设置, 最后调用show()显示toast.
注意, 如果不需要setView的情况下, 请不要使用Toast的构造方法来创建toast对象, 而是应该使用makeText(Context, int, int)方法来创建Toast.
参考: http://developer.android.com/guide/topics/ui/notifiers/toasts.html