OnCreateLayoutWithSizeSpec
OnCreateLayoutWithSizeSpec
is the same as OnCreateLayout but the layout can be resolved with a specified width and height. Use this instead of OnCreateLayout
if the LayoutSpec returns a layout tree that depends on its own and/or its children's size.
For example, a spec might use Component A
if that fits within the specified width or use Component B
instead.
The annotated method must return a Component and can receive the following arguments.
Required:
- ComponentContext
- int (width spec)
- int (height spec)
Optional and annotated arguments:
The annotation processor will validate this and other invariants in the API at build time. The optional and annotated arguments are inputs which should be used to create the layout of the spec.
For example:
@LayoutSpec
class MyComponentSpec {
@OnCreateLayoutWithSizeSpec
static Component onCreateLayoutWithSizeSpec(
ComponentContext c,
int widthSpec,
int heightSpec) {
final Component textComponent =
Text.create(c).textSizeSp(16).text("Some text to measure.").build();
// UNSPECIFIED sizeSpecs will measure the text as being one line only,
// having unlimited width.
final Size textOutputSize = new Size();
textComponent.measure(
c,
SizeSpec.makeSizeSpec(0, UNSPECIFIED),
SizeSpec.makeSizeSpec(0, UNSPECIFIED),
textOutputSize);
// Small component to use in case textComponent does not fit within the current layout.
final Component imageComponent = Image.create(c).drawableRes(R.drawable.ic_launcher).build();
// Assuming SizeSpec.getMode(widthSpec) == EXACTLY or AT_MOST.
final int layoutWidth = SizeSpec.getSize(widthSpec);
final boolean textFits = (textOutputSize.width <= layoutWidth);
return textFits ? textComponent : imageComponent;
}
}
Content copied to clipboard