Welcome to FutureAppLaboratory

v=(*^ワ^*)=v

Update UI With Observer

| Comments

Sometimes I need to update UI from different Fragments. But it seems that writing update method in each Fragment is absurd if I have a lot of Fragment to handle with.

Here is a better solution by using Observer pattern, IMO.

Sample

    1. Define an EventObject, which is a event(or message) will be passed to Observer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ViewPagerTabsUIEventObject extends EventObject {

    public enum EventType {
        LABEL_ON,
        LABEL_OFF,
    }

    private EventType mEventType;

    public ViewPagerTabsUIEventObject(Object source, EventType eventType) {
        super(source);
        mEventType = eventType;
    }

    public static final String TAG = "ViewPagerTabsUIEventObject";

    public EventType getEventType() {
        return this.mEventType;
    }
}
    1. Define an Observable, which will dispatch event or message to Observer.
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ViewPagerTabsObservable extends Observable {

    public static final String TAG = "ViewPagerTabsObservable";

    public static ViewPagerTabsObservable sInstance = new ViewPagerTabsObservable();

    public ViewPagerTabsObservable() { }

    public void notice(ViewPagerTabsUIEventObject eventObject) {
        setChanged();
        notifyObservers(eventObject);
    }
}
    1. Caller. Use a shared instance of Observable to dispatch event to Observer.
1
2
ViewPagerTabsUIEventObject eventObject = new ViewPagerTabsUIEventObject(this, EventType.LABEL_OFF);
ViewPagerTabsObservable.sInstance.notice(eventObject);
    1. Receiver, which implements Observer interface.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ViewPagerTabs extends LinearLayout implements Observer {

    /* ... */

    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ViewPagerTabsUIEventObject eventObject = (ViewPagerTabsUIEventObject) data;
        switch (eventObject.getEventType()) {
        case LABEL_OFF:
            // do something
            break;
        case LABEL_ON:
            // do something else
            break;
        default:
            break;
        }
    }

}

Comments