您的当前位置:首页正文

EventBus使用实例,观察者模式

2024-11-30 来源:个人技术集锦

依赖

 

compile 'org.greenrobot:eventbus:3.0.0'

构造函数方法类(用于传递参数)

 

public class ChangeFragmentEvent {
    private int viewId;
    private String ass;

    public ChangeFragmentEvent(int id,String ss) {
        this.viewId = id;
        this.ass=ss;
    }

    public int getViewId() {
        return viewId;
    }
    public String getstring (){
        return ass;
    }

    public void setViewId(int viewId) {
        this.viewId = viewId;
    }
}

注册

 

EventBus.getDefault().register(this);

activity监听回调

    @org.greenrobot.eventbus.Subscribe(threadMode = ThreadMode.POSTING)//MAIN
    public void onMessageEvent(ChangeFragmentEvent changeFragmentEvent) {
        tomapte.setText("vvvvv555"+changeFragmentEvent.getstring());
//        tomapte.setText("vvvvv555");//dosomething
    }

开启调用EventBus

 

EventBus.getDefault().post(new ChangeFragmentEvent(3333,"laile"));

取消注册

 

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    Log.v("lgq", "......11..onDestroy....");
}

 

显示全文