初见EventBus
优点
方便各种乱七八糟东西之间的通信,不墨迹
初级使用
1.创建事件类
package com.lw.lw.eventbustest;
/**
* Created by liwei on 2017/8/30.
*/
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.在MainActivity注册事件并对接受到的事件进行处理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv);
jumpSecondBtn = (Button) findViewById(R.id.btn);
jumpSecondBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
//注册事件
EventBus.getDefault().register(this);
}
//处理事件,方法名字可以瞎jier写
@Subscribe( threadMode = ThreadMode.MAIN)
public void getEventBusMessage(MessageEvent messageEvent){
textView.setText(messageEvent.getMessage());
}
//取消事件
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
3.发送事件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv = (TextView) findViewById(R.id.textView);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().post(new MessageEvent("汪汪汪"));
finish();
}
});
}
Over 在这里诅咒我呆变成宋仲基
好想画这种啊啊啊啊
网友评论