[EventBus]使用帮助

1.添加依赖:compile 'org.greenrobot:eventbus:3.1.1'

2.创建一个消息类

3.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_bus)

        EventBus.getDefault().register(this)

        btn_eventbus.onClick {
            startActivity<MainActivity>()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent) {
        Toast.makeText(this,"test received event message", Toast.LENGTH_LONG)
        btn_eventbus.text = event.message
        Log.d("test", "test")
    }

 流程是注册--->接受----->注销

注意,哪里注册就在那里需要@Subscribe要不会报错

4.发送信息:

class EventPresent {

    fun sendMessage(){
        println("================")
        EventBus.getDefault().post(MessageEvent("test event send"))
    }
}

 这样EventBus的Activity就能接收到post的信息

参考:

1.http://blog.csdn.net/itachi85/article/details/52205464

相关推荐