title: Communicating with Other Fragments - alternative design
body: <p>According to <a href="http://developer.android.com/training/basics/fragments/communicating.html" rel="nofollow">Android developer pages</a>, fragments communicate through its host activity. This tends to produce rigid fragment &lt;-> host relationships and verbose implementations of even the simplest event propagations - it gets worse if you have multiple recipients, etc.</p>
  
  <p>I'd like to propose an alternative approach, which has worked for me. Please let me know if you see a problem with it, particularly regarding memory leaks, as I have actors registering with a singleton. </p>
  
  <p>In summary, I have an EventHub singleton which fragments post their events to, not caring if there is anybody listening "on the other side". My fragments (or activity) are registering with the EventHub passing its Handler instances:</p>
  
  <p><strong>Activity/fragment listening for events from other fragments:</strong></p>
  
  <pre><code>public void onResume()
  {
      super.onResume();
  
      // Register self with the hub and start receiving events
      EventHub.getInstance().register( handler_ );
      ...
  }
  
  /** Don't leak handlers. */
  @Override
  public void onPause() {
      // Remove self from the event hub.
      EventHub.getInstance().unregister( handler_ );
  }
  
  /** Dispatch events. */
  private Handler handler_ = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          switch( msg.what ) {
              ....
          }
      }
  };
  </code></pre>
  
  <p><strong>Fragment emitting events:</strong></p>
  
  <pre><code>    button.setOnClickListener(new View.OnClickListener()
          {
              @Override
              public void onClick(View v) {
                  EventHub.getInstance().post( Message m );
              }
          });
  </code></pre>