导入包 implementation 'org.greenrobot:eventbus:3.1.1' implementation 'com.jakewharton:butterknife:9.0.0-rc2'
public class MainActivity extends AppCompatActivity { @BindView(R.id.buton_bu) Button butonBu; @BindView(R.id.text_tv) TextView textTv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); EventBus.getDefault().register(this); } @OnClick(R.id.buton_bu) public void onViewClicked() { Intent intent = new Intent(); intent.setClass(MainActivity.this,SecondActivity.class); startActivity(intent); } @Subscribe(threadMode = ThreadMode.MAIN) public void userEventBus(FirstEvent firstEvent) { textTv.setText(firstEvent.getName()); } @Override protected void onDestroy() { super.onDestroy(); //注销注册 EventBus.getDefault().unregister(this); } }
第二界面
public class SecondActivity extends AppCompatActivity { @BindView(R.id.edit_et) EditText editEt; @BindView(R.id.search_bu) Button searchBu; private String str; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activiy); ButterKnife.bind(this); } @OnClick({ R.id.search_bu}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.search_bu: str = editEt.getText().toString(); EventBus.getDefault().post(new FirstEvent(str)); finish(); break; } } }
实体类
public class FirstEvent { public String name; public FirstEvent(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "FirstEvent{" + "name='" + name + '\'' + '}'; } }
MainActivity布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >
<Button android:id="@+id/buton_bu" android:text="点击" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/text_tv" android:layout_width="match_parent" android:layout_height="122dp" android:textSize="18sp" android:gravity="center"/>
</LinearLayout>
布局SecondActivity <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <EditText android:id="@+id/edit_et" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/search_bu" android:text="发生数据到主界面" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>