標籤:
Android事件驅動編程(二)
——歡迎轉載,請註明出處 http://blog.csdn.net/asce1885 ,未經本人同意請勿用於商業用途,謝謝——
原文連結:https://medium.com/google-developer-experts/event-driven-programming-for-android-part-ii-b1e05698e440
本文Gitbooks連結:http://asce1885.gitbooks.io/android-rd-senior-advanced/content/androidshi_jian_qu_dong_bian_cheng_ff08_er_ff09.html
在前面的文章中我們簡單介紹了事件驅動編程,現在讓我們看看真實的代碼並介紹EventBus的基礎用法。
首先我會參考(從EventBus倉庫截取的),介紹在事件驅動編程中扮演中心角色的實體們。
事件匯流排EventBus:串連所有其他實體的中央通訊通道;
事件Event:發生的動作,幾乎可以是任何事情(應用啟動,收到某些資料,使用者互動等等);
訂閱者Subscriber:訂閱者監聽事件匯流排,當匯流排中有事件在流通時,訂閱者將被觸發;
發行者Publisher:往事件匯流排發送事件;
唯有親身實踐才能有清晰的認知,下面就讓我們來看一個簡單的例子:
宿主Activity
宿主Activity需要在它的onCreate函數中註冊EventBus:
EventBus.getDefault().register(this);
註冊之後,宿主Activity就可以從匯流排上讀取資料了,我們同時需要在Activity的onDestroy函數中反註冊EventBus:
EventBus.getDefault().unregister(this);
Activity會捕獲到兩個不同的事件:一個用於更新ActionBar,一個用於載入第一個fragment。我們會編寫兩個onEvent函數來處理這兩個事件:
public void onEvent(ShowFragmentEvent event) { getFragmentManager().beginTransaction().replace(R.id.container, event.getFragment()).addToBackStack(null).commit();}public void onEvent(UpdateActionBarTitleEvent e) { getActionBar().setTitle(e.getTitle()); }
事件
每個事件需要在類中聲明,事件中可以包含變數:
public final class ShowFragmentEvent { private Fragment fragment; public ShowFragmentEvent(Fragment fragment) { this.fragment = fragment; } public Fragment getFragment() { return fragment; }}
The Fragments
接下來我們要來建立fragments。第一個fragment包含一個用來開啟第二個fragment的按鈕,第二個fragment包含一個按鈕,當點擊按鈕時,將重新整理TextView。Fragments也需要註冊和反註冊EventBus,為了得到一個簡潔的結構,我們將定義一個BaseFragment來封裝這些公用的操作。
現在讓我們建立更多一些動作,第一個fragment將通過下面的函數來開啟第二個fragment:
@OnClick(R.id.first_button) public void firstButtonClick() { EventBus.getDefault().post(new ShowFragmentEvent(new SecondFragment())); }
需要注意的是這裡我使用了ButterKnife中定義的註解,它可以產生更簡單和整潔的代碼。如果你還沒有使用過它,那麼現在應該開始使用了。
第二個fragment的按鈕會向事件匯流排發送一個事件,用來更新TextView:
EventBus.getDefault().post(new UpdateTextEvent(getString(R.string.text_updated)));
第二個fragment同時需要監聽這個事件,這樣當它接收到這個事件時,可以相應的改變文字顯示:
public void onEvent(UpdateTextEvent event) { textView.setText(event.getTitle()); }
我們的簡單應用具有兩個fragments,通過事件實現兩個fragments之間的通訊,一個fragment通過事件獲得更新。我已經把代碼上傳到GitHub上面,你可以檢出並看一下。
一個關鍵的問題是如何逐步升級一個事件驅動的架構。在下一篇文章中我將介紹一個簡潔的,可理解的架構,來支援Android中的事件驅動編程。
Android事件驅動編程-基於EventBus(二)