EnventBus传值

 

 

implementation 'org.greenrobot:eventbus:3.0.0'
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {

    private Button but2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        initView();
    }

    private void initView() {
        but2 = (Button) findViewById(R.id.but2);

        but2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but2:
                User user = new User("你好");
                EventBus.getDefault().post(user);
                break;
        }
    }


}

 

 

 

 

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button but1;

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

    }

    private void initView() {
        but1 = (Button) findViewById(R.id.but1);

        but1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but1:
            startActivity(new Intent(this,Main2Activity.class));
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Even(User user) {
  but1.setText(user.getName());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}

 

你可能感兴趣的:(安卓,模板)