1.首先添加依赖
compile 'org.greenrobot:eventbus:3.0.0'
2.我们要创建一个类 , 里面写我们要传送的属性
public class FirstEvent { private String msg; public FirstEvent(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
3.然后我们要在mainactivity中注册eventbus
public class MainActivity extends AppCompatActivity { private Button button; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.BT); textView = (TextView) findViewById(R.id.TV); //注册EventBus EventBus.getDefault().register(this); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this , MyActivity.class); startActivity(intent); } }); } //EventBus3.0必须要加上此注解 否则会报错 @Subscribe public void onEventMainThread(FirstEvent firstEvent){ String msg = "接收到的消息"+firstEvent.getMsg(); textView.setText(msg); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); } @Override protected void onDestroy() { super.onDestroy(); //解除注册 EventBus.getDefault().unregister(this); } }
4.我们在另一个activity中用来发送消息
public class MyActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); button = (Button) findViewById(R.id.btn_first_event); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //发送消息 EventBus.getDefault().post(new FirstEvent("chen xue da sha bi")); finish(); } }); } }
5.两个布局 主布局是一个button , textview 另一个布局是一个button