简单的EventBus传值

EventBus更像是startActvity的双向传值

1.首先通过一个实体类,来携带参数

public class FirstEvent {
    private final String msg;

    public FirstEvent(String msg) {
        this.msg=msg;
    }

    public String getMsg() {
        return msg;
    }
}
2.在main里面写

public class MainActivity extends AppCompatActivity {

    private Button btn_try;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //注册EventBus
        EventBus.getDefault().register(this);
        btn_try = (Button) findViewById(R.id.btn_try);
        tv = (TextView) findViewById(R.id.tv);
//为按钮添加监听
        btn_try.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),SecondActivity.class));
            }
        });

    }

   public void  onEventMainThread(FirstEvent event){
       tv.setText("来自第二个Acitity的数据"+event.getMsg());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        注销
        EventBus.getDefault().unregister(this);
    }
}
3.第二个SecondActivity代码
 
  

public class SecondActivity extends AppCompatActivity {

    @InjectView(R.id.btn_first_event)
    Button btnFirstEvent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ButterKnife.inject(this);

    }

    @OnClick(R.id.btn_first_event)
    public void onClick() {
        EventBus.getDefault().post(new FirstEvent("我是Second我要发给Main信息"));

    }
}

4.gradle里面的要添加的包

compile 'de.greenrobot:eventbus:2.4.0'
compile 'com.jakewharton:butterknife:6.1.0'

5.在main.xml里面写




    

6.在Second.xml里面写



    



你可能感兴趣的:(简单的EventBus传值)