OnCreateLayout
This annotation is used in conjugation with LayoutSpec. The framework calls the method annotated with OnCreateLayout
in the LayoutSpec to resolve a layout. The framework can call onCreateLayout
from any thread and as many times as required. This method should not create side effects. The annotated method must return a Component and can receive the following arguments.
Required:
- ComponentContext
Optional annotated arguments:
The annotation processor will validate this and other invariants in the API at build time. The annotated arguments are inputs which should be used to create the layout of the spec.
For example:
@LayoutSpec
public class HeaderSpec {
@OnCreateLayout
static Component onCreateLayout(
ComponentContext c,
@Prop String title,
@Prop String subtitle,
@Prop String imageUrl,
@State boolean isSelected) {
return Column.create(c)
.paddingDip(YogaEdge.ALL, 8)
.backgroundColor(isSelected ? Color.WHITE : Color.GREEN)
.child(
Image.create(c)
.url(imageUrl)
.marginDip(YogaEdge.BOTTOM, 4)
)
.child(
Text.create(c)
.text(title)
.textSizeSp(16)
.marginDip(YogaEdge.BOTTOM, 4)
)
.child(
Text.create(c)
.text(subtitle)
.textSizeSp(12)
)
.build();
}
}
Notice how imageUrl
, title
, subtitle
and isSelected
are used to set properties on different components within the layout. In the example above, the layout tree has a root container with three children stacked vertically (Column.create(c)
). The first child is an Image component (Image.create(c)
) which renders and image from a URL (similar to Android's ImageView
). The second and third children are Text components (Text.create(c)
) which renders a text equivalent to the Android TextView
.