导入依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
manActivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="aaaaa"
android:id="@+id/text" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="aaa" />
</LinearLayout>
MainActivity.java:
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post("121111111111111111111");
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void setText(String str) {
TextView textView = findViewById(R.id.text);
textView.setText(str);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
1、首先要在onCreate处注册EventBus,然后销毁Activity的时候,要取消注册,不能忘记了。
2、给按钮点下的时候加个监听事件,发送一个消息,我这里就随便发送了一个String。
3、写一个public方法,给它标记注解,这样这个方法就会接收到步骤2发送的String,然后就可以处理自己的业务逻辑了。