在自定义的单例Application中添加如下代码:
public class BaseApp extends Application {
//.....自己的其他代码,该BaseApp必是单例的
// 全局的 handler 对象
private final Handler APPHANDLER = new Handler();
// 全局的 Toast 对象
private FlexibleToast flexibleToast;
// ........其他操作
// 在初始化资源的地方创建Toast
flexibleToast = new FlexibleToast(this);
public void toastShowByBuilder(final FlexibleToast.Builder builder) {
if (Looper.myLooper() != Looper.getMainLooper()) {
getAppHandler().post(new Runnable() {
@Override
public void run() {
flexibleToast.toastShow(builder);
}
});
} else {
flexibleToast.toastShow(builder);
}
}
//.....others
}
现在就可以在想Toast的地方使用了。
使用方法:
buidler中设置想要的样式,包括显示什么元素,位置,时长。
FlexibleToast.Builder builder = new FlexibleToast.Builder(this).setGravity(FlexibleToast.GRAVITY_TOP).setFirstText("first").setSecondText("second=" + System.currentTimeMillis());
BaseApp.getApp().toastShowByBuilder(builder);
如果想利用自己定义的布局,可以这样使用:
其中R.layout.layout_toast_with_two_text是自己定义的布局,此时builder中对ImageView和TextView的设置都是无效的了。
View toastView = LayoutInflater.from(this).inflate(R.layout.layout_toast_with_two_text, null, false);
TextView tvOne = (TextView) toastView.findViewById(R.id.tv_text_one);
TextView tvTwo = (TextView) toastView.findViewById(R.id.tv_text_two);tvOne.setText("customer one");tvTwo.setText("customer two");
FlexibleToast.Builder builder = new FlexibleToast.Builder(this).setCustomerView(toastView);BaseApp.getApp().toastShowByBuilder(builder);
关于初始化Toast的Context,源码中的doc是这样写的: