EventBus3.0

来源:互联网 发布:美国留学 知乎 编辑:程序博客网 时间:2024/04/24 23:04

依赖

   compile 'org.greenrobot:eventbus:3.0.0'

main_activity布局

 <Button
        android:id="@+id/bt_jump"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

main_activity类

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册EventBus
        EventBus.getDefault().register(this);


        findViewById(R.id.bt_jump).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,OtherActivity.class));
            }
        });
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMsg(MessageEvent event){
        Toast.makeText(this, "接收到消息:"+event.msg+","+event.code, Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}


other_activity布局

<Button
        android:id="@+id/bt_send"
        android:text="发送"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


other_activity类

public class OtherActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        findViewById(R.id.bt_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new MessageEvent("使用EventBus3.0来发送消息",200));
                finish();
            }
        });
    }
}


MessageEvent类

public class MessageEvent {
    public String msg;
    public int code;


    public MessageEvent(String msg, int code) {
        this.msg = msg;
        this.code = code;
    }
}

原创粉丝点击