mikebritton
|
|
« on: April 05, 2011, 01:02:38 » |
|
When trying to figure out how to send events from Activities to Mediators, I first created interface InteractionListener for the Mediator to implement:
package com.britton.apps.puremvcboilerplate.view;
import com.britton.apps.puremvcboilerplate.view.event.InteractionEvent;
public interface InteractionListener { public void interactionReceived(InteractionEvent event); public void configureListeners(InteractionListener m); }
Implementation in Mediator:
@Override public void onRegister() { super.onRegister(); configureListeners(this); }
@Override public void configureListeners(InteractionListener m) { this.getApplication().addListener(m); }
@Override public void interactionReceived(InteractionEvent event) { Log.d(TAG, "Event Received"); }
In my experimental app, Activity is subclassed as InteractionActivity (which could also be an abstract class):
package com.britton.apps.puremvcboilerplate.view;
import java.util.ArrayList; import java.util.List;
import android.app.Activity;
public class InteractionEmitterActivity extends Activity { public List listeners; public InteractionEmitterActivity() { listeners = new ArrayList(); } public synchronized void addListener(InteractionListener il) { listeners.add(il); }
public synchronized void removeListener(InteractionListener il) { listeners.remove(il); } }
And in ApplicationActivity, the subclass, where there's a Button ready to trigger this miraculous handler:
private void initDisplay() { btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { InteractionEvent ie = new InteractionEvent(this); Iterator it = listeners.iterator(); while (it.hasNext()) { InteractionListener il = (InteractionListener) it.next(); il.interactionReceived(ie); } } }); }
So now, any Activity that extends InteractionEmitterActivity can, by contract, send InteractionEvents to the Mediator actor.
Here's the InteractionEvent:
package com.britton.apps.puremvcboilerplate.view.event;
import java.util.EventObject;
public class InteractionEvent extends EventObject { public InteractionEvent(Object source) { super(source); } }
I realize this is very Flex-like; in fact, I kept thinking about Signals when I wrote it! I've had success with them. Maybe that's another route.
Mike
|