美文网首页
Android App中使用全局Toast

Android App中使用全局Toast

作者: 好奇的小刺猬 | 来源:发表于2016-05-17 18:43 被阅读3199次

自定义的FlexibleToast主要功能:

  1. 支持默认格式,自上向下布局为ImageView、TextView、TextView,三个控件可以自由组合显示或隐藏
  2. 支持Top,Center,Bottom的位置显示,默认Bottom和TOAST_SHORT显示。
  3. 可以传入自定义的layout的View,支持其他自定义的显示
  4. 共用一个Toast对象,防止多次Toast重叠以及并显示时间的累加,该控件仅保留最后一次的文本、显示时间等设置。
  5. 在app自己自定义的Application中创建的Toast,Activity,Fragment,Adapter中都可以直接调用。
  6. 主线程或者子线程可以直接调用。
  7. 使用简单,先创建一个控制toast各种属性的builder,然后直接调用toastShowByBuilder(builder)即可。

配置和使用步骤:

  1. 在自定义的单例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的地方使用了。

  2. 使用方法:
    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);

  3. 关于初始化Toast的Context,源码中的doc是这样写的:

The context to use. Usually your {@link android.app.Application} or {@link android.app.Activity} object.

Demo中将new Toast放到了自己的Application中,这样那么子线程使用就能直接show,而子线程如果在使用的时候才new Toast,会Crash,要么就要用handler去post到主线程中toast。也就是要保证toast的创建在主线程总。ToastDemo中的SensorList页面中有这两个例子。

  1. Demo地址:
    https://github.com/maoranbian/MTime

相关文章

网友评论

      本文标题:Android App中使用全局Toast

      本文链接:https://www.haomeiwen.com/subject/xcmirttx.html