EventBus

1.根据文章最前面所讲的EventBus使用步骤,首先我们需要定义一个消息事件类:

public class MessageEvent {

    private String message;

    public MessageEvent(String message) {
this.message = message;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
}
2.
在ActivityA界面中我们首先需要注册订阅事件:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册事件
EventBus.getDefault().register(this);
......
}
3.然后在onDestory()方法中取消订阅:
@Override
protected void onDestroy() {
super.onDestroy();
//取消事件注册
EventBus.getDefault().unregister(this);
}
4.当然还要定义一个消息处理的方法:
@Subscribe(threadMode = ThreadMode.MainThread)
public void onShowMessageEvent(MessageEvent messageEvent) {
mMessageView.setText("Message from SecondActivity:" + messageEvent.getMessage());
}
5.至此,消息订阅者我们已经定义好了,我们还需要在ActivityB中发布消息:
findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = mMessageET.getText().toString();
if(TextUtils.isEmpty(message)) {
message = "defaule message";
}
EventBus.getDefault().post(new MessageEvent(message));
}
});
05-11 17:13