Eventbus的使用步骤:
假设有个需求实现由A界面跳转到B界面,当关闭B界面时,需要传递数据到A界面,使用Eventbus进行实现。
一.项目中引用Eventbus的库
compile 'org.greenrobot:eventbus:3.0.0'
二.新建一个实体类,定义需要传递的数据信息。比如新建实体类person类
public class Person { private String name;//用户姓名 private int age;//用户年龄 public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
三.代码中注册Eventbus和解除注册
在activity的oncreat方法中完成注册
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this);//注册 }在actvity的onDestroy方法中解除注册
protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this);//解除注册 }四。发送消息 调用Eventbus的post方法
EventBus.getDefault().post(new Person("刘备", 33));
五.接收传来的数据进行处理
@Subscribe(threadMode = ThreadMode.MAIN)//必须加上这句否则会报错 public void onEventMainThread(Person person) { String msg = person.getName() + person.getAge(); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); }完整代码如下
这事Mainactivy用于注册Eventbus和接收返回的数据
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, SecondClass.class); startActivity(intent); } }); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(Person person) { String msg = person.getName() + person.getAge(); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }这是第二个Activity用于返回要传递的数据
public class SecondClass extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventBus.getDefault().post(new Person("刘备", 33)); finish(); } }); } }