1.EventBus 在activity中传值的使用(观察者模式) :布局
分为三步 1.事件发生 2.观察者(订阅事件) 3.被观察者或者观察对象(发送事件)post
如下以activty(发送事件) 向fragment(订阅事件)跳转为例this
第一步:事件 定义(放数据mode)对象
public String type;
public String content;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
第二步:发送事件事件
/实例化碎片对象
UpFragment upFragment = new UpFragment();
//得到碎片管理器
FragmentManager manager = OneActivity.this.getFragmentManager();
// 得到事务
FragmentTransaction transaction = manager.beginTransaction();
// 把碎片添加到activity中,R.id.left指的是activity中布局的id
transaction.replace(R.id.ll_one, upFragment);
// 提交
transaction.commit();
EventBus.getDefault().post(new MyEvent());
第三步:订阅事件:事务
在oncreat()方法中注册:EventBus.getDefault().register(this);get
在ondestory()方法中取消注册:EventBus.getDefault().unregister(this);it
最主要的方法:io
// 接收数据(onEvent是jar包中的)
public void onEventMainThread(MyEvent event) {
Log.e("1", "" + event.getContent());
tvRes.setText("接收的消息:" + event.getType());
}
另外fragment向fragment传数据的状况同上 可是订阅事件的是放全部fragment的activity中。event