This page was machine-translated from Portuguese and may contain errors. The Portuguese version is canonical.
The lifecycle
The CrossFly lifecycle has three levels: the application, the window (screen), and the component.
Level 1 — application: the bootstrap (Main)
Main is libGDX’s ApplicationListener. When the platform comes up, libGDX calls Main.create() on the
paint thread, and Main:
- detects the platform and initializes the runtime and the device configuration;
- resolves the name of the main window (from a
classnameargument or fromgetMainWindow()); - instantiates that window by reflection (
Class.forName(...)→newInstance()) and calls itsonShow().
After that, libGDX calls render() (on each rendered frame) and resize() — always on the paint thread.
Level 2 — window: onShow()
Each screen is a subclass of Window that builds its UI in onShow() (with super.onShow()):
public class TelaHome extends Window {
@Override public void onShow() throws Exception {
super.onShow();
setLayout(new VerticalLayout());
add(LAY_AUTO, new Label("Início"));
}
}
Why onShow() and not the constructor? In the constructor, the bounds and hierarchy are not yet
ready — Screen.width/height and the window size are only valid afterward. Building the UI too early
leads to wrong measurements. (The window stack and navigation are in The window stack.)
Level 3 — component: onAdd(firstTime) / onRemove()
When a component enters the tree, the framework calls onAdd(boolean firstTime); when it leaves,
onRemove(). This is where you initialize and release resources:
public class Relogio extends Component {
private Timer timer;
@Override public void onAdd(boolean firstTime) throws Exception {
super.onAdd(firstTime);
if (firstTime) timer = iniciarTimer(); // resources that must exist only once
}
@Override public void onRemove() {
if (timer != null) timer.cancel(); // always release on exit
super.onRemove();
}
}
What does firstTime distinguish? A component can be added, removed, and re-added.
firstTime == true only the first time — use it for setup that should not repeat. onRemove() is the
cleanup counterpart: cancel timers, listeners, cursors.
General rule: do not initialize UI/resources in the constructor. Use
onShow()(window) andonAdd(firstTime)(component), where bounds and hierarchy are already valid.
See also
- Apply: Navigate between screens
- Next: State and data flow