-
Notifications
You must be signed in to change notification settings - Fork 6
Presenter
The Presenter
is the class that handles logic and passes data to the View
via the Container
interface.
A Presenter
instance is a singleton instance in its screen scope, meaning it will survive events such as orientation changes. It can thus be used for both the portrait and landscape views. The lifecycle of the Presenter
consists of only two methods:
-
onControlGained(Container, ActivityComponent)
- When theView
is attached to the window; -
onControlLost()
- When theView
has gone away.
The Presenter
communicates with the View
using the Container
interface. It is therefore possible to create two separate View
classes for portrait and landscape, managed by one and the same Presenter
instance. Optionally, you can use the View
directly instead of the interace, but best practices suggest you use an interface.
You can get a hold of the Container
using container()
, which returns an Optional
instance similar to Guava's Optional. This instance contains a reference to the Container
if and only if it is called between onControlGained(...)
and onControlLost()
. It is therefore wise to check whether container().isPresent()
returns true
, before accessing the instance with container().get()
.
A simple Presenter
class which keeps track of a counter is given below:
class CounterPresenter extends Presenter<MyContainer, ActivityComponent> {
private int mCounter;
MyPresenter() {
mCounter = 0;
}
@Override
public void onControlGained(@NonNull MyContainer container, @NonNull ActivityComponent activityComponent) {
container.setCounterText(String.valueOf(mCounter));
}
public void onIncrementButtonClicked() {
if (!container().isPresent()) {
/* Fail-safe return. */
return;
}
mCounter++;
container().get().setCounterText(String.valueOf(mCounter));
}
}