Android Toast[译]
原文连接:http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Toasts
Toast弹窗是对用户操作的简单反馈。Toast的大小会根据要显示的内容自适应并且仅在当前Activity可见和可交互。例如:在离开写邮件界面时,提示“已保存草稿”,让你知道之后你还能继续编辑。当超时后,Toast会自动消失。
基本用法
首先,使用任意一个makeText()
方法初始化Toast对象。这个方法有三个参数:Context、Toast显示的消息、Toast显示时间。makeText()方法返回一个正确初始化的Toast对象。调用show()
方法可以显示Toast通知。以下是一个示例:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
//字符串资源的ID
int resId = R.string.sample;
//另一种makeText()
//Toast toast = Toast.makeToast(context,resId,duration);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
以上的例子能满足大部分Toast通知的需求。然而,你也可能需要设置Toast显示的位置甚至自定义Toast显示消息的布局。接下来会告诉你如何实现这些。
你也可以选择不持有Toast对象而是通过链接方法来实现,例如:
Toast.makeText(context, text, duration).show();
Toast位置
Toast默认是在屏幕下方居中显示。使用setGravity(int, int, int)
方法你可以改变Toast的显示位置。这个方法有三个参数:位置常量Gravity
,x上的偏移量,y上的偏移量。
例如,你想在屏幕左上方显示Toast,你可以这么设置:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
如果你想让Toast显示位置往右偏移,则可以通过增加第二个参数xOffset来实现。如果你想让Toast显示位置往下偏移,则可以通过增加第三个参数yOffset来实现。
创建自定义View的Toast
如果仅显示文本的Toast不能满足要求,你可以创建自定义View的Toast。创建一个自定义View,首先你要通过XML布局文件或者代码创建View,然后用setView(view)方法将根view传递进去。
例如:
<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是”toast_layout_root”,一定要使用这个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();
首先,使用getLayoutInflater()
或getSystemService()
获取LayoutInflater
对象,之后用LayoutInflater
对象的inflate(int,ViewGroup)
载入布局。第一个参数是布局的id,第二个参数是布局的根View。你可以使用载入的布局获取更多的view对象,如ImageView和TextView。最后,使用Toast(Context)
创建一个Toast并设置一些参数,如gravity和duration。之后使用setView(View)
设置显示的view。这样,你就能通过show()
方法显示自定义的布局。
Note:不要使用构造函数创建Toast,除非你需要自定义Toast的View。如果你没有创建自定义Toast的需求,那么请使用
makeText(Context,int,int)
创建Toast。