zoukankan      html  css  js  c++  java
  • EventBus的简单使用

    文章中引用了张鸿洋大神的博客,链接在此:http://blog.csdn.net/lmj623565791/article/details/40794879 和 http://blog.csdn.net/lmj623565791/article/details/40920453

    此文章为本人学习记录所用,如有不对,欢迎指正!

    进入正题

    使用步骤:

      1.新建一个类

      2.在使用页面进行注册/反注册/传递数据

      3.在接收页面进行接收

    具体代码:

      1.新建一个类

    public class Event
    {
    public static class ItemListEvent
    {
    private List<Item> items;

    public ItemListEvent(List<Item> items)
    {
    this.items = items;
    }

    public List<Item> getItems()
    {
    return items;
    }
    }
    }
      2.在使用页面进行注册/反注册/传递数据
        a.注册语句,注册的作用是当页面创建时,先扫描整个页面,把所有onEvent的方法全部以键值对的方式存储起来,这样当执行传递数据语句时,根据传入的参数,直接从Map中找出对应的方法,利用反射进行调用
          EventBus.getDefault().register(this);
        b.反注册语句
          EventBus.getDefault().unregister(this);
        c.传递数据语句
          EventBus.getDefault().post(new Event.ItemListEvent(Item.ITEMS));
      3.在页面进行接收
        此处需要明确一个问题,就是EventBus包含4个ThreadMode:onEventpostThread、onEventMainThread、onEventBackgroundThread、onEventAsync。其中:
        onEventpostThread:表示当前方法会在当前发布事件的线程里执行
        onEventMainThread:表示无论发布事件是在哪个线程,都会在主线程中执行
        onEventBackgroundThread:表示如果发布事件的线程并非主线程,则直接在同一线程里执行,但是如果发布事件的线程是主线程,则直接加入后台任务池队列,只用线程池一个接着一个调用
        onEventAsync:和onEventBackgroundThread相似,但不同的是没有onEventBackgroundThread中的一个接着一个调用,而是直接调用
        接收时需要调用onEventpostThread、onEventMainThread、onEventBackgroundThread、onEventAsync方法中的一个。如:
    public void onEventMainThread(Event.ItemListEvent event)
    {
    setListAdapter(new ArrayAdapter<Item>(getActivity(),
    android.R.layout.simple_list_item_activated_1,
    android.R.id.text1, event.getItems()));
    }

        
        
  • 相关阅读:
    transform:translate -50%解释
    无缝滚动条
    css二维画面练习-扑克牌
    css二维动画
    ORM了解
    socket总结
    2016/9/23总结电脑内容
    winform控件跨线程委托
    HttpRequestMessage
    vue设置每个页面的头部title
  • 原文地址:https://www.cnblogs.com/FruitBoy/p/6296922.html
Copyright © 2011-2022 走看看