标签:点击 word function 地方 mod ram gre 注册 ide
compile ‘org.greenrobot:eventbus:3.0.0‘
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;
}
}
分别在FirstActivity的onCreate()方法和onDestory()方法里,进行注册EventBus和解除注册。
//接收activate
public class FirstActivity extends AppCompatActivity {
private Button mButton;
private TextView mText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
mButton = (Button) findViewById(R.id.btn1);
mText = (TextView) findViewById(R.id.tv1);
mText.setText("今天是星期三");
//在需要订阅事件的地方注册事件
EventBus.getDefault().register(this);
jumpActivity();
}
//点击事件
private void jumpActivity() {
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
//接收
@Subscribe(threadMode = ThreadMode.MAIN)
public void Event(MessageEvent messageEvent) {
mText.setText(messageEvent.getMessage());
}
//销毁
@Override
protected void onDestroy() {
super.onDestroy();
if(EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
}
在这里,事件的处理线程在主线程,是因为,我要让TextView去显示值。
在 SecondActivity里去进行事件的发送。(发送活动)
public class SecondActivity extends AppCompatActivity {
private Button mButton2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
mButton2=(Button) findViewById(R.id.btn2);
jumpActivity();
}
private void jumpActivity() {
mButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送
EventBus.getDefault().post(new MessageEvent("欢迎大家浏览我写的博客"));
finish();
}
});
}
}
标签:点击 word function 地方 mod ram gre 注册 ide
原文地址:https://www.cnblogs.com/sunjian43792901/p/11130279.html