初识EventBus

第一步,gradle里配置:
compile ‘org.greenrobot:eventbus:3.0.0’

第二步: 注册eventBus:
EventBus.getDefault().register(this); //注册

第三步,注销注册EventBus:
@Override
protected void onDestroy() {
super.onDestroy();
if (EventBus.getDefault().isRegistered(this)){
EventBus.getDefault().unregister(this); //解除注册
}
}

Demo如下:
一:
public class EventBusDemo extends BaseActivity {

private Button mButton;
private TextView mText;

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

    mButton = (Button) findViewById(R.id.btn1);
    mText = (TextView) findViewById(R.id.txt1);
    mText.setText("今天是星期三");
    EventBus.getDefault().register(this);  //注册
    jumpActivity();
}

private void jumpActivity() {
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(EventBusDemo.this,EventBusDemoSecondActivity.class);
            startActivity(intent);
        }
    });
}

@Subscribe
public void Event(MessageEvent messageEvent){
    mText.setText(messageEvent.getMessage());
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (EventBus.getDefault().isRegistered(this)){
        EventBus.getDefault().unregister(this);  //解除注册
    }
}

}

二二:

public class EventBusDemoSecondActivity extends BaseActivity {

private Button btn2;
private ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.event_bus_demo_second);
    btn2 = (Button) findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            EventBus.getDefault().post(new MessageEvent("欢迎大家浏览我的博客"));
            finish();
        }
    });

    img = (ImageView) findViewById(R.id.image_loader);

  //  ImageloaderUtils.getInstance(this).disPlayImg("url", img);

}

}

你可能感兴趣的:(android)