Android開發中EventBus的使用

來源:互聯網
上載者:User

標籤:reg   content   .post   模式   ret   event   ttext   fragment   觀察者   

1.EventBus 在activity中傳值的使用(觀察者模式) :

分為三步 1.事件發生   2.觀察者(訂閱事件)  3.被觀察者或者觀察對象(發送事件)

以下以activty(發送事件) 向fragment(訂閱事件)跳轉為例

第一步:事件 定義(放資料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);

在ondestory()方法中取消註冊:EventBus.getDefault().unregister(this);

最主要的方法:

//  接收資料(onEvent是jar包中的)
public void onEventMainThread(MyEvent event) {
Log.e("1", "" + event.getContent());
tvRes.setText("接收的訊息:" + event.getType());
}

 

另外fragment向fragment傳資料的情況同上  但是訂閱事件的是放所有fragment的activity中。

 

Android開發中EventBus的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.