android开发者不可避免的会与toast打交道,这是一个全局提醒,只要用于消息的提示等等。但是不同的手机toast的展示形式可能会存在不一样,为此我们需要定制自己的Toast组件…(主要是通过加载自己的布局文件,定制化实现Toast对象)
(一)Toast的基础用法
Toast.makeText(context, "No network connection.", duration).show();
我们看一下makeText方法的实现:
/**
* Make a standard toast that just contains a text view.
*
* @param context The context to use. Usually your {@link android.app.Application}
* or {@link android.app.Activity} object.
* @param text The text to show. Can be formatted text.
* @param duration How long to display the message. Either {@link #LENGTH_SHORT} or
* {@link #LENGTH_LONG}
*
*/
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
主要是创建一个Toast对象,然后加载布局文件,设置显示msg的消息和时间长短。。。
其中Toast源码中定义了两个常量分别别是显示的时间长短:
/**
* Show the view or text notification for a short period of time. This time
* could be user-definable. This is the default.
* @see #setDuration
*/
public static final int LENGTH_SHORT = 0;
/**
* Show the view or text notification for a long period of time. This time
* could be user-definable.
* @see #setDuration
*/
public static final int LENGTH_LONG = 1;
(二)自定义布局文件初始化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();
自定义布局文件:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://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"/>
这样以后我们使用自己的Toast对象,就能保证不同的手机上Toast的展示形式是一致的了。。。(当前一些App都已经是MD风格了,我们可以考虑实现MD风格的Toast展示)