?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:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.bw.eventbus.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:id="@+id/text" />
</LinearLayout>
//需要jar包 EventBus2.4.jar
public class MainActivity extends AppCompatActivity { private Button mBtn; private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); EventBus.getDefault().register(this); mBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(MainActivity.this,Main2Activity.class); startActivity(intent); } }); } private void initView() { mBtn = (Button) findViewById(R.id.btn); mText = (TextView) findViewById(R.id.text); } //最常用的一个方法 名字不能自己定义必须是这个 public void onEventMainThread(User message) { String string = message.getString(); mText.setText(string); } //关闭 @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
public class Main2Activity extends AppCompatActivity { /** * Button */ private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); initView(); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventBus.getDefault().post(new User("你嘞草原你嘞马,你想杂耍你杂耍")); finish(); } }); } private void initView() { mButton = (Button) findViewById(R.id.button); } }