Android官方文档—User Interface(Toasts)

Toasts

Toast在小弹出窗口中提供有关操作的简单反馈。它仅填充消息所需的空间量,并且当前活动保持可见和交互。例如,在发送电子邮件之前导航离开电子邮件会触发“草稿保存”吐司,以便您知道以后可以继续编辑。超时后,Toasts会自动消失。

如果需要用户对状态消息的响应,请考虑使用通知。

基础


首先,使用makeText()方法之一实例化Toast对象。此方法有三个参数:应用程序上下文,文本消息和Toast的持续时间。它返回一个正确初始化的Toast对象。您可以使用show()显示Toast通知,如以下示例所示:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

此示例演示了大多数Toast通知所需的一切。你应该很少需要别的东西。但是,您可能希望以不同的方式定位吐司,甚至使用您自己的布局而不是简单的文本消息。以下部分描述了如何执行这些操作。

你也可以链接你的方法,避免持有Toast对象,如下所示:

Toast.makeText(context, text, duration).show();

定位你的吐司


标准吐司通知出现在屏幕底部附近,水平居中。您可以使用setGravity(int,int,int)方法更改此位置。这接受三个参数:重力常数,x位置偏移和y位置偏移。

例如,如果您确定吐司应该出现在左上角,您可以像这样设置重力:

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

如果要将位置微移到右侧,请增加第二个参数的值。要轻推它,请增加最后一个参数的值。

创建自定义Toast视图


如果简单的短信不够,您可以为Toast通知创建自定义布局。要创建自定义布局,请在XML或应用程序代码中定义View布局,并将根View对象传递给setView(View)方法。

例如,您可以使用以下XML(保存为layout / custom_toast.xml)为右侧屏幕截图中显示的Toast创建布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              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是“custom_toast_container”。您必须使用此ID和XML布局文件“custom_toast”的ID来扩充布局,如下所示:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                (ViewGroup) findViewById(R.id.custom_toast_container));

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,然后使用inflate(int,ViewGroup)从XML中扩展布局。第一个参数是布局资源ID,第二个参数是根视图。您可以使用此膨胀布局在布局中查找更多View对象,因此现在可以捕获并定义ImageView和TextView元素的内容。最后,使用Toast(Context)创建一个新的Toast并设置Toast的一些属性,例如重力和持续时间。然后调用setView(View)并将其传递给膨胀的布局。现在,您可以通过调用show()来显示具有自定义布局的Toast。

注意:除非要使用setView(View)定义布局,否则不要将公共构造函数用于Toast。如果您没有要使用的自定义布局,则必须使用makeText(Context,int,int)来创建Toast。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章