10. Deixando responsivo
O que você vai aprender: fazer o app se adaptar a qualquer tela sem um pixel fixo. Pré-requisitos: Persistindo dados.
Exemplo completo (copiar, colar e rodar)
App adaptativo: onReposition() troca o arranjo por orientação (2 colunas em landscape, 1 em
portrait) sem recriar estado, usando Relative/Gap e Screen. Compila como está.
package com.exemplo;
import dev.crossfly.ui.*;
import dev.crossfly.ui.layout.*;
public class MainWindow extends Window
{
private final Component painel = new Component();
private final Component listaBox = new Component();
private final Component detalheBox = new Component();
@Override
public void onShow() throws Exception
{
super.onShow();
setLayout(new VerticalLayout());
listaBox.setLayout(new VerticalLayout());
listaBox.add(LAY_AUTO, new Label("Lista"));
detalheBox.setLayout(new VerticalLayout());
detalheBox.add(LAY_AUTO, new Label("Detalhe"));
boolean largo = Screen.minSize >= 600; // breakpoint: menor lado (estável ao girar)
add(LAY_AUTO, new Label(largo ? "Tablet/desktop" : "Telefone"));
add(LAY_FILL, painel);
onReposition(); // arranjo inicial
}
@Override
protected void onReposition() throws Exception
{
painel.removeAll();
if (Screen.isLandscape) { // 2 colunas: lista | detalhe
painel.setLayout(new HorizontalLayout());
painel.add(0.4f, listaBox);
painel.add(0.6f, detalheBox);
} else { // 1 coluna
painel.setLayout(new VerticalLayout());
painel.add(LAY_FILL, listaBox);
}
painel.setValidLayout(false);
}
}
Os trechos abaixo mostram só o miolo (o que vai dentro de
onShow()). Para rodar, coloque-os no esqueletoMainWindowacima.
As ferramentas
Relative.ofFont(1.5f); // escala com a fonte/DPI
Relative.ofScreen(0.8f, ScreenSize.MIN); // fração do MENOR lado (adapta portrait/landscape)
Gap.ofFont(0.5f); // espaçamento que escala
add(LAY_FILL, comp); // uma área elástica por eixo
Breakpoint com Screen.minSize
Use o menor lado — estável quando o aparelho gira:
boolean largo = Screen.minSize >= 600; // tablet/desktop
Trocar o arranjo por orientação — onReposition()
Quando a estrutura deve mudar (1 coluna em portrait, 2 em landscape), sobrescreva onReposition()
(chamado no resize) — sem recriar estado:
@Override protected void onReposition() throws Exception {
painel.removeAll();
if (Screen.isLandscape) { // 2 colunas: lista | detalhe
painel.setLayout(new HorizontalLayout());
painel.add(0.4f, listaBox);
painel.add(0.6f, detalheBox);
} else { // 1 coluna
painel.setLayout(new VerticalLayout());
painel.add(LAY_FILL, listaBox);
}
}
Constrói neste passo
O app vira adaptativo — telefone em portrait, tablet/desktop em landscape — sem pixel fixo.
Recapitulando
Relative/Gap/LAY_FILL = responsivo automático; Screen.minSize = breakpoint; onReposition()
troca o arranjo preservando o estado.