直接进入正题
EventBus主要就是用来传递消息,有三个常用方法:
(1)EventBus.getDefault().register(this);//用来注册EventBus
(2)EventBus.getDefault().unregister(this);//用来注销EventBus,记住注册之后一定要注销
(3)EventBus.getDefault().post(new TestEvent("1111"));//传递数据,例如传递1111
下面来最简单的使用:
(1)在OnCreate()生命周期中注册EventBus,不管是在Activity中还是Fragment中使用,一定记住要在OnCreate()中注册;
(2)在OnDestory()中注销EventBus;
(3)例如在AActivity中我要使用BActivity传递的数据;
AActivity中注册和注销EventBus,并接受数据,BActivity中传递数据。
BActicity中自定义传递数据的类TextEvent
public class TestEvent{ public String testStr; public TestEvent(String testStr){ this.testStr=testStr; } }在BActivity中传递数据EventBus.getDefault().post(new TestEvent("1111"));
在AActivity中接受数据,定义一个方法onEventMainThread方法
public void onEventMainThread(TestEvent event) { if (event != null) { if (event.testStr!= null) { Toast.makeText(getActivity(), event.testStr, Toast.LENGTH_SHORT).show(); } } }
总结:就是这么简单,就是这么牛。