EventBus

添加依赖包

    implementation 'org.greenrobot:eventbus:3.0.0'

首界面

public class MainActivity extends AppCompatActivity {

    private Button button;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }
   //操作
    private void initData() {
       //点击跳转传值
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //粘性事件
                EventBus.getDefault().postSticky(new MessageWrap("Hello EventBus!"));
                Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                startActivity( intent );
            }
        });
    }
   //布局
    private void initView() {
        button = (Button) findViewById(R.id.button);
    }
}

外部类

public class MessageWrap {
    private String name;
    public MessageWrap(String name) {
        this.name = name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

接受界面

public class Main2Activity extends AppCompatActivity {
    private TextView textview;
    private static final String TAG = "SecondActivity";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        initView();
        EventBus.getDefault().register( this );
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageWrap event) {
        Log.i(TAG, "message is " + event.getName());
        // 更新界面
        textview.setText(event.getName());
        // 移除粘性事件
        EventBus.getDefault().removeStickyEvent(event);
    }
    //销毁
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    //初始化
    public void initView() {   
        textview = (TextView) findViewById(R.id.textview);
    }
}

你可能感兴趣的:(EventBus)