当前位置: 移动互联网学院 > Android开发 > Android Toast用法教程
Android Toast用法教程 时间:2017-04-14     来源:Android开发学习网

Toast是Android中用来显示显示信息的一种机制,和Dialog不一样的是,Toast是没有焦点的,而且Toast显示的时间有限,过一定的时间就会自动消失。今天就为大家讲解一下Android Toast的使用方法。

如何在Android程序中添加Toast?

用 make() 方法创建一个 Toast 实例,然后调用 show() 方法。

Toast.makeText(context, "No network connection.", duration).show();

Duration

使用 makeText() 方法的 duration 参数 或者 setDuration 方法指定 Snackbar 在屏幕上显示多长时间。

// 你只能使用这两个预定义的常量

duration = Toast.LENGTH_SHORT; // 2000 秒

duration = Toast.LENGTH_LONG; // 3500 秒

toast.setDuration(duration);

Cancel

可以在任何时候使用 cancel() 方法手动的去隐藏 Toast 。

Toast toast= Toast.make(view, text, duration).show();

toast.cancel(); //隐藏吐司

如果在它显示的时候关闭它或者在不想显示的时候它仍然显示,通常你不需要去调用这个方法。它会在持续适当的时间之后自己消失。

Positioning

用 setGravity() 可以改变 Toast 的显示位置。

int gravity = Gravity.CENTER; // Toast在屏幕中的位置,当前属性设置在屏幕中间

int xOffset = 0; // 水平偏移距离

int yOffset = 0; // 垂直偏移距离

Toast toast= Toast.make(view, text, duration);

toast.setGravity(gravity, xOffset, yOffset);

如何设置Toast样式?

用代码直接设置Toast样式

// 创建 Toast 实例

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

// 设置消息颜色

TextView textView= (TextView) toast.getView().findViewById(android.R.id.message);

textView.setTextColor(Color.YELLOW);

// 设置背景颜色

toast.getView().setBackgroundColor(getResources().getColor(R.color.indigo));

通过自定义 View设置Toast样式

I. 在 layout.xml 文件内的任意位置声明你的自定义 View。

xmlns:android="//schemas.android.com/apk/res/android"

android:id="@+id/txtMessage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:drawableStart="@drawable/ic_report_problem"

android:drawablePadding="8dp"

android:paddingTop="8dp"

android:paddingBottom="8dp"

android:paddingLeft="16dp"

android:paddingRight="16dp"

android:gravity="center"

android:textColor="@android:color/white"

android:textSize="16dp"

android:text="No connection."

android:background="@color/indigo"/>

II. 通过 setView() 方法设置你的自定义 View 到 Toast 。

// 创建 Toast 实例

Toast toast = new Toast(getApplicationContext());

// 创建自定义 view

View view = getLayoutInflater().inflate(R.layout.toast_view, null);

// 设置自定义 view

toast.setView(view);

// 设置显示持续时间

toast.setDuration(Toast.LENGTH_LONG);

// 设置位置

int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);

toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);

// 显示 Toast

toast.show();
关于Android Toast的使用方法掌握了没?更多Android开发技术文章,请持续关注我们!