Layout Specs
- Java
- Kotlin
A layout spec is the logical equivalent of a composite view on Android. It simply groups existing components together in an immutable layout tree.
Implementing a layout spec is very simple: you only need to write one method annotated with @OnCreateLayout
which returns an immutable tree of Component objects.
Let's start with a simple example:
As you can see, layout spec classes use the @LayoutSpec
annotation.
The method annotated with @OnCreateLayout
must have ComponentContext as its first argument followed by a list of arguments annotated with @Prop
. The annotation processor will validate this and other invariants in the API at build time.
In the example above, the layout tree has a root Container with two children stacked horizontally (Row.create
) and vertically centered (Align.CENTER
).
The first child is a SolidColor component that takes a colorRes
prop and has a 40dp width and height.
The second child is a Text component that takes a prop named text
and fills the remaining horizontal space available in MyComponent
by using grow(1f)
(equivalent to Android's layoutWeight
from LinearLayout
). The text size is defined in my_text_size
dimension resource.
You can check the full Yoga documentation to see all the layout features that the framework exposes.