基本使用
(1)自定义一个类,可以是空类,比如:
public class FirstEvent {
private String mMsg;
public FirstEvent(String msg) {
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
(2)在要接收消息的页面注册:
eventBus.register(this);
(3)发送消息
eventBus.post(new FirstEvent event);
(4)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):
public void onEventMainThread(FirstEvent event) {}
(5)解除注册
eventBus.unregister(this);
实战
public class MainActivity extends AppCompatActivity {
Button btn;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
btn = (Button) findViewById(R.id.btn_try);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(intent);
}
});
}
@Subscribe
public void onEventMainThread(FirstEvent event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
public class SecondActivity extends AppCompatActivity {
private Button btn_FirstEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));
finish();
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_try"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="btn_bty"/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
</LinearLayout>
activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_first_event"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="First Event"/>
</LinearLayout>