//先导依赖
compile 'org.greenrobot:eventbus:3.0.0'
//一个消息的实体类也就是Bean类
public class EventBusStickMessage { public String Message; public EventBusStickMessage(String message) { Message = message; } }
//发送者的Activity
public class MainActivity extends AppCompatActivity { String s="我是最帅的"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View view){ EventBus.getDefault().postSticky(new EventBusStickMessage(s) ); startActivity( new Intent(this,ShowActivity.class)); } }
//发送者Activity的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:onClick="send" android:text="向主页面使用EventBus发送一个事件" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout>
//接受者的Activity
public class ShowActivity extends AppCompatActivity implements View.OnClickListener { /** * 接受一个粘性事件事件 */ private Button mBtn; /** * wret */ private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); initView(); } private void initView() { mBtn = (Button) findViewById(R.id.btn); mBtn.setOnClickListener(this); mText = (TextView) findViewById(R.id.text); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn: //判断如果已经注册过了,那就不注册了,如果不做判断那么就会报一个已经注册过的错误,程序也会崩溃 if(!EventBus.getDefault ().isRegistered (this)){ EventBus.getDefault ().register(this); } break; } } //接收值 粘性事件必须要加的参数sticky = true @Subscribe(threadMode = ThreadMode.MAIN,sticky = true) public void request(EventBusStickMessage eMessage){ mText.setText (eMessage.Message); } @Override protected void onDestroy() { super.onDestroy (); //移除所有的粘性事件 EventBus.getDefault ().removeAllStickyEvents (); //取消注册 EventBus.getDefault ().unregister (this); }
}
//接受者的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.eventbus__nianxingshijian.ShowActivity"> <Button android:id="@+id/btn" android:text="接受一个粘性事件事件" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/text" android:text="wret" android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>