EventBus事件总线库

GIthub官方地址:

https://github.com/greenrobot/EventBus

使用步骤

EventBus in 3 steps
  1. Define events:
    public class MessageEvent { /* Additional fields if needed */ }

  2. Prepare subscribers
    Register your subscriber (in your onCreate or in a constructor):
    eventBus.register(this);

    Declare your subscribing method:
    @Subscribe
    public void onEvent(AnyEventType event) {/* Do something */};

  3. Post events:
    eventBus.post(event);
   Gradle中添加一下代码:
 compile 'org.greenrobot:eventbus:3.0.0'
    

Maven:

<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus</artifactId>
    <version>3.0.0</version>
</dependency>
测试如下:

public class EventAActivity extends Activity implements View.OnClickListener {

    private Button mButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_a);
        mButton = (Button) findViewById(R.id.event_button);
        EventBus.getDefault().register(this);
        mButton.setOnClickListener(this);
    }

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

    @Subscribe
    public void onEventMainThread(MessageEvent event) {
        Toast.makeText(EventAActivity.this, event.message, Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.event_button) {
            Intent intent = new Intent(this, EventBActivity.class);
            startActivity(intent);

        }
    }
}

另一个Activity
public class EventBActivity extends Activity implements View.OnClickListener {

    private Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_b);
//        EventBus.getDefault().register(this);
        mButton = (Button) findViewById(R.id.event_b_button);
        mButton.setOnClickListener(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
    }
}


   当在BActivity中点击发送按钮的时候,可以把消息传递到AActivity中。






你可能感兴趣的:(EventBus事件总线库)