Toast – 简短消息提示工具
TL;DR
为避免 Toast 重叠, 推荐使用如下工具方法弹出 Toast:
private static Toast mToast = null;
public static void showToast(Context context, int resId) {
if(mTosat == null){
mToast = Toast.makeText(context, resId, Toast.LENGTH_SHORT);
} else {
mTost.setText(resId);
}
mToast.show();
}
如果使用多个 Toast 连续调用 show() 方法显示消息,这些消息会成队列式弹出,并且无法取消,出现 Toast 滞留现象。
静态方法
Toast makeText (Context context, int resId, int duration)
Toast makeText (Context context, CharSequence text, int duration)
使用该静态方法可以方便得传入内容和显示时长来获得一个 Toast 对象. 位置默认在底部居中,可另行设置.
除非需要自定义 Toast View , 否则不要用构造方法创建 Toast.
构造方法
创建空的 toast 对象。需要单独设置参数(时长,内容,位置等)
Toast(Context context)
主要参数: 时长, 位置, 内容
设置显示时长
void setDuration (int duration) /** 有效参数: Toast.LENGTH_SHORT, Toast_LENGTH_LONG */
设置显示位置
void setGravity (int gravity, int xOffset, int yOffset) /** 如显示在左上角: toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0); */
设置显示内容
void setText (int resId) void setText (CharSequence s) /** 默认的 Toast 包含一个 TextView, 只是简单地显示一条文本. */
这里要注意的是与 TextView 的 setText 方法一样, 如果传入 int 型参数, 会将其当做字符串资源 id. 如果要显示数字, 要先转成字符串类型。尤其是设置从服务端获取的数据时要留意一下数据类型。
设置显示样式
自定义 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”, 这是必需值 , 不可更改.
对 Toast 进行设置
LayoutInflater inflater = getLayoutInflater(); // 将布局文件转成 View 对象 View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_container)); // 获取承载消息的 TextView 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();