Created
March 16, 2016 06:29
-
-
Save jacquesgiraudel/43ea55a668979712385b to your computer and use it in GitHub Desktop.
observer-snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ObserverActivity extends Activity implements Observer{ | |
... | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
... | |
MyObservable myObservable = new MyObservable(); | |
// Registering of the observer (here the activity) | |
myObservable.addObserver(this); | |
// Changing the state of the observable | |
myObservable.setValue("Hello ! "); | |
} | |
// Update of the observer on a state change notification | |
@Override | |
public void update(Observable observable, Object data) { | |
textView.setText(((MyObservable)observable).getValue()); | |
} | |
class MyObservable extends Observable { | |
private String mValue; | |
public String getValue() { | |
return mValue; | |
} | |
public void setValue(String mValue) { | |
this.mValue = mValue; | |
// Mark the change of state | |
setChanged(); | |
// Notification of the change for update | |
notifyObservers(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment