{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

Modifier

public interface Modifier

Known direct subclasses
CombinedModifier

A node in a Modifier chain.

Modifier.Companion

The companion object Modifier is the empty, default, or starter Modifier that contains no elements.

Modifier.Element

A single element contained within a Modifier chain.

Known indirect subclasses
DrawCacheModifier

DrawModifier implementation that supports building a cache of objects to be referenced across draw calls

DrawModifier

A Modifier.Element that draws into the space of the layout.

FocusEventModifier

This interface is deprecated. Use FocusEventModifierNode instead

FocusOrderModifier

This interface is deprecated. Use Modifier.focusProperties() instead

FocusRequesterModifier

This interface is deprecated. Use FocusRequesterModifierNode instead

InspectableModifier.End
InspectableModifier

Annotates a range of modifiers in a chain with inspector metadata.

LayoutModifier

A Modifier.Element that changes how its wrapped content is measured and laid out.

ModifierLocalConsumer

A Modifier that can be used to consume ModifierLocals that were provided by other modifiers to the left of this modifier, or above this modifier in the layout tree.

ModifierLocalProvider

A Modifier that can be used to provide ModifierLocals that can be read by other modifiers to the right of this modifier, or modifiers that are children of the layout node that this modifier is attached to.

ModifierNodeElement

A Modifier.Element which manages an instance of a particular Modifier.Node implementation.

OnGloballyPositionedModifier

A modifier whose onGloballyPositioned is called with the final LayoutCoordinates of the Layout when the global position of the content may have changed.

OnPlacedModifier

A modifier whose onPlaced is called after the parent LayoutModifier and parent layout has been placed and before child LayoutModifier is placed.

OnRemeasuredModifier

A modifier whose onRemeasured is called when the layout content is remeasured.

ParentDataModifier

A Modifier that provides data to the parent Layout.

PointerInputModifier

A Modifier.Element that can interact with pointer input.

RelocationModifier

This interface is deprecated. Please use BringIntoViewResponder instead.

RemeasurementModifier

A Modifier.Element that provides a Remeasurement object associated with the layout node the modifier is applied to.

SemanticsModifier

A Modifier.Element that adds semantics key/value for use in testing, accessibility, and similar use cases.


An ordered, immutable collection of modifier elements that decorate or add behavior to Compose UI elements. For example, backgrounds, padding and click event listeners decorate or add behavior to rows, text or buttons.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Text(
    "Hello, World!",
    Modifier
        .padding(16.dp) // Outer padding; outside background
        .background(color = Color.Green) // Solid element background color
        .padding(16.dp) // Inner padding; inside background, around text
)

Modifier implementations should offer a fluent factory extension function on Modifier for creating combined modifiers by starting from existing modifiers:

import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

class FancyModifier(val level: Float) : Modifier.Element

fun Modifier.fancy(level: Float) = this.then(FancyModifier(level))

Row(
    Modifier
        .fancy(1f)
        .padding(10.dp)) {
    // content
}

Modifier elements may be combined using then. Order is significant; modifier elements that appear first will be applied first.

Composables that accept a Modifier as a parameter to be applied to the whole component represented by the composable function should name the parameter modifier and assign the parameter a default value of Modifier. It should appear as the first optional parameter in the parameter list; after all required parameters (except for trailing lambda parameters) but before any other parameters with default values. Any default modifiers desired by a composable function should come after the modifier parameter's value in the composable function's implementation, keeping Modifier as the default parameter value. For example:

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun PaddedColumn(modifier: Modifier = Modifier) {
    Column(modifier.padding(10.dp)) {
        // ...
    }
}

The pattern above allows default modifiers to still be applied as part of the chain if a caller also supplies unrelated modifiers.

Composables that accept modifiers to be applied to a specific subcomponent foo should name the parameter fooModifier and follow the same guidelines above for default values and behavior. Subcomponent modifiers should be grouped together and follow the parent composable's modifier. For example:

import androidx.compose.foundation.layout.Row
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

@Composable
fun ButtonBar(
    onOk: () -> Unit,
    onCancel: () -> Unit,
    modifier: Modifier = Modifier,
    buttonModifier: Modifier = Modifier
) {
    Row(modifier) {
        Button(onCancel, buttonModifier) {
            Text("Cancel")
        }
        Button(onOk, buttonModifier) {
            Text("Ok")
        }
    }
}

Summary

Nested types

public static class Modifier.Companion implements Modifier

The companion object Modifier is the empty, default, or starter Modifier that contains no elements.

public interface Modifier.Element extends Modifier

A single element contained within a Modifier chain.

public abstract class Modifier.Node implements DelegatableNode

The longer-lived object that is created for each Modifier.Element applied to a androidx.compose.ui.layout.Layout.

Public methods

abstract boolean
all(
    @NonNull Function1<@NonNull Modifier.Element, @NonNull Boolean> predicate
)

Returns true if predicate returns true for all Elements in this Modifier or if this Modifier contains no Elements.

abstract boolean
any(
    @NonNull Function1<@NonNull Modifier.Element, @NonNull Boolean> predicate
)

Returns true if predicate returns true for any Element in this Modifier.

abstract @NonNull R
<R extends Object> foldIn(
    @NonNull R initial,
    @NonNull Function2<@NonNull R, @NonNull Modifier.Element, @NonNull R> operation
)

Accumulates a value starting with initial and applying operation to the current value and each element from outside in.

abstract @NonNull R
<R extends Object> foldOut(
    @NonNull R initial,
    @NonNull Function2<@NonNull Modifier.Element, @NonNull R, @NonNull R> operation
)

Accumulates a value starting with initial and applying operation to the current value and each element from inside out.

default @NonNull Modifier

Concatenates this modifier with another.

Extension functions

default final @NonNull Modifier
AlignmentLineKt.paddingFrom(
    @NonNull Modifier receiver,
    @NonNull AlignmentLine alignmentLine,
    @NonNull Dp before,
    @NonNull Dp after
)

A Modifier that can add padding to position the content according to specified distances from its bounds to an alignment line.

default final @NonNull Modifier
AlignmentLineKt.paddingFrom(
    @NonNull Modifier receiver,
    @NonNull AlignmentLine alignmentLine,
    @NonNull TextUnit before,
    @NonNull TextUnit after
)

A Modifier that can add padding to position the content according to specified distances from its bounds to an alignment line.

default final @NonNull Modifier
AlignmentLineKt.paddingFromBaseline(
    @NonNull Modifier receiver,
    @NonNull Dp top,
    @NonNull Dp bottom
)

A Modifier that positions the content in a layout such that the distance from the top of the layout to the baseline of the first line of text in the content is top, and the distance from the baseline of the last line of text in the content to the bottom of the layout is bottom.

default final @NonNull Modifier
AlignmentLineKt.paddingFromBaseline(
    @NonNull Modifier receiver,
    @NonNull TextUnit top,
    @NonNull TextUnit bottom
)

A Modifier that positions the content in a layout such that the distance from the top of the layout to the baseline of the first line of text in the content is top, and the distance from the baseline of the last line of text in the content to the bottom of the layout is bottom.

default final @NonNull Modifier
AlphaKt.alpha(@NonNull Modifier receiver, float alpha)

Draw content with modified alpha that may be less than 1.

default final @NonNull Modifier
AnimationModifierKt.animateContentSize(
    @NonNull Modifier receiver,
    @NonNull FiniteAnimationSpec<@NonNull IntSize> animationSpec,
    Function2<@NonNull IntSize, @NonNull IntSizeUnit> finishedListener
)

This modifier animates its own size when its child modifier (or the child composable if it is already at the tail of the chain) changes size.

default final @NonNull Modifier
AspectRatioKt.aspectRatio(
    @NonNull Modifier receiver,
    float ratio,
    boolean matchHeightConstraintsFirst
)

Attempts to size the content to match a specified aspect ratio by trying to match one of the incoming constraints in the following order: Constraints.maxWidth, Constraints.maxHeight, Constraints.minWidth, Constraints.minHeight if matchHeightConstraintsFirst is false (which is the default), or Constraints.maxHeight, Constraints.maxWidth, Constraints.minHeight, Constraints.minWidth if matchHeightConstraintsFirst is true.

default final @NonNull Modifier
BackgroundKt.background(
    @NonNull Modifier receiver,
    @NonNull Color color,
    @NonNull Shape shape
)

Draws shape with a solid color behind the content.

default final @NonNull Modifier
BackgroundKt.background(
    @NonNull Modifier receiver,
    @NonNull Brush brush,
    @NonNull Shape shape,
    float alpha
)

Draws shape with brush behind the content.

default final @NonNull Modifier
@ExperimentalFoundationApi
BasicMarqueeKt.basicMarquee(
    @NonNull Modifier receiver,
    int iterations,
    @NonNull MarqueeAnimationMode animationMode,
    int delayMillis,
    int initialDelayMillis,
    @NonNull MarqueeSpacing spacing,
    @NonNull Dp velocity
)

Applies an animated marquee effect to the modified content if it's too wide to fit in the available space.

default final @NonNull Modifier
BlurKt.blur(
    @NonNull Modifier receiver,
    @NonNull Dp radius,
    @NonNull BlurredEdgeTreatment edgeTreatment
)

Draw content blurred with the specified radii.

default final @NonNull Modifier
BlurKt.blur(
    @NonNull Modifier receiver,
    @NonNull Dp radiusX,
    @NonNull Dp radiusY,
    @NonNull BlurredEdgeTreatment edgeTreatment
)

Draw content blurred with the specified radii.

default final @NonNull Modifier
BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull BorderStroke border,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a border and a shape and clip it.

default final @NonNull Modifier
BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Brush brush,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a width, a brush and a shape and clip it.

default final @NonNull Modifier
BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Color color,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a width, a color and a shape and clip it.

default final @NonNull Modifier

Modifier that can be used to send bringIntoView requests.

default final @NonNull Modifier

A parent that can respond to BringIntoViewRequester requests from its children, and scroll so that the item is visible on screen.

default final @NonNull Modifier
ClickableKt.clickable(
    @NonNull Modifier receiver,
    boolean enabled,
    String onClickLabel,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks via input or accessibility "click" event.

default final @NonNull Modifier
ClickableKt.clickable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    String onClickLabel,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks via input or accessibility "click" event.

default final @NonNull Modifier
@ExperimentalFoundationApi
ClickableKt.combinedClickable(
    @NonNull Modifier receiver,
    boolean enabled,
    String onClickLabel,
    Role role,
    String onLongClickLabel,
    Function0<Unit> onLongClick,
    Function0<Unit> onDoubleClick,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks, double clicks and long clicks via input or accessibility "click" event.

default final @NonNull Modifier
@ExperimentalFoundationApi
ClickableKt.combinedClickable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    String onClickLabel,
    Role role,
    String onLongClickLabel,
    Function0<Unit> onLongClick,
    Function0<Unit> onDoubleClick,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks, double clicks and long clicks via input or accessibility "click" event.

default final @NonNull Modifier
ClipKt.clip(@NonNull Modifier receiver, @NonNull Shape shape)

Clip the content to shape.

default final @NonNull Modifier

Clip the content to the bounds of a layer defined at this modifier.

default final @NonNull Modifier

Clips bounds of scrollable container on main axis while leaving space for background effects (like shadows) on cross axis.

default final @NonNull Modifier
ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies.

default final @NonNull Modifier
@ExperimentalComposeUiApi
ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies.

default final @NonNull Modifier
@ExperimentalComposeUiApi
ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object keys,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies.

default final @NonNull Modifier
@ExperimentalComposeUiApi
ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    Object key2,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies.

default final @NonNull Modifier
@ExperimentalComposeUiApi
ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    Object key2,
    Object key3,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies.

default final @NonNull Modifier
DrawModifierKt.drawBehind(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> onDraw
)

Draw into a Canvas behind the modified content.

default final @NonNull Modifier
DrawModifierKt.drawWithCache(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull CacheDrawScope, @NonNull DrawResult> onBuildDrawCache
)

Draw into a DrawScope with content that is persisted across draw calls as long as the size of the drawing area is the same or any state objects that are read have not changed.

default final @NonNull Modifier

Creates a DrawModifier that allows the developer to draw before or after the layout's contents.

default final @NonNull Modifier

This method is deprecated. Use systemGestureExclusion

default final @NonNull Modifier

This method is deprecated. Use systemGestureExclusion

default final @NonNull Modifier
FocusChangedModifierKt.onFocusChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusChanged
)

Add this modifier to a component to observe focus state events.

default final @NonNull Modifier
FocusEventModifierKt.onFocusEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusEvent
)

Add this modifier to a component to observe focus state events.

default final @NonNull Modifier

This method is deprecated. Replaced by focusTarget

default final @NonNull Modifier

Add this modifier to a component to make it focusable.

default final @NonNull Modifier
FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull FocusOrderUnit> focusOrderReceiver
)

This method is deprecated. Use focusProperties() instead

default final @NonNull Modifier
FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester
)

This method is deprecated. Use focusRequester() instead

default final @NonNull Modifier
FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester,
    @ExtensionFunctionType @NonNull Function1<@NonNull FocusOrderUnit> focusOrderReceiver
)

This method is deprecated. Use focusProperties() and focusRequester() instead

default final @NonNull Modifier

This modifier allows you to specify properties that are accessible to focusTargets further down the modifier chain or on child layout nodes.

default final @NonNull Modifier
FocusRequesterModifierKt.focusRequester(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester
)

Add this modifier to a component to request changes to focus.

default final @NonNull Modifier

Creates a focus group or marks this component as a focus group.

default final @NonNull Modifier
FocusableKt.focusable(
    @NonNull Modifier receiver,
    boolean enabled,
    MutableInteractionSource interactionSource
)

Configure component to be focusable via focus system or accessibility "focus" event.

default final @NonNull Modifier

Calls onPositioned whenever the bounds of the currently-focused area changes.

default final @NonNull Modifier

A Modifier.Node that makes content draw into a draw layer.

default final @NonNull Modifier
GraphicsLayerModifierKt.graphicsLayer(
    @NonNull Modifier receiver,
    float scaleX,
    float scaleY,
    float alpha,
    float translationX,
    float translationY,
    float shadowElevation,
    float rotationX,
    float rotationY,
    float rotationZ,
    float cameraDistance,
    @NonNull TransformOrigin transformOrigin,
    @NonNull Shape shape,
    boolean clip,
    RenderEffect renderEffect,
    @NonNull Color ambientShadowColor,
    @NonNull Color spotShadowColor,
    @NonNull CompositingStrategy compositingStrategy
)

A Modifier.Element that makes content draw into a draw layer.

default final @NonNull Modifier

A Modifier.Element that adds a draw layer such that tooling can identify an element in the drawn image.

default final @NonNull Modifier
HoverableKt.hoverable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    boolean enabled
)

Configure component to be hoverable via pointer enter/exit events.

default final @NonNull Modifier
IndicationKt.indication(
    @NonNull Modifier receiver,
    @NonNull InteractionSource interactionSource,
    Indication indication
)

Draws visual effects for this component when interactions occur.

default final @NonNull Modifier
InspectableValueKt.inspectable(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Use this to group a common set of modifiers and provide InspectorInfo for the resulting modifier.

default final @NonNull Modifier

Reserves at least 48.dp in size to disambiguate touch interactions if the element would measure smaller.

default final @NonNull Modifier
IntrinsicKt.height(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the preferred height of the content to be the same as the min or max intrinsic height of the content.

default final @NonNull Modifier
IntrinsicKt.requiredHeight(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the height of the content to be exactly the same as the min or max intrinsic height of the content.

default final @NonNull Modifier
IntrinsicKt.requiredWidth(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the width of the content to be exactly the same as the min or max intrinsic width of the content.

default final @NonNull Modifier
IntrinsicKt.width(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the preferred width of the content to be the same as the min or max intrinsic width of the content.

default final @NonNull Modifier
KeyInputModifierKt.onKeyEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onKeyEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events when it (or one of its children) is focused.

default final @NonNull Modifier
KeyInputModifierKt.onPreviewKeyEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onPreviewKeyEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events when it (or one of its children) is focused.

default final @NonNull Modifier

Tag the element with layoutId to identify the element within its parent.

default final @NonNull Modifier

Creates a LayoutModifier that allows changing how the wrapped element is measured and laid out.

default final @NonNull Modifier

Creates an intermediate layout intended to help morph the layout from the current layout to the lookahead (i.e. pre-calculated future) layout.

default final @NonNull Modifier
@ExperimentalFoundationApi
MagnifierKt.magnifier(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> sourceCenter,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> magnifierCenter,
    float zoom,
    @NonNull MagnifierStyle style,
    Function1<@NonNull DpSizeUnit> onSizeChanged
)

Shows a Magnifier widget that shows an enlarged version of the content at sourceCenter relative to the current layout node.

default final @NonNull Modifier

A Modifier that can be used to consume ModifierLocals that were provided by other modifiers to the left of this modifier, or above this modifier in the layout tree.

default final @NonNull Modifier

A Modifier that can be used to provide ModifierLocals that can be read by other modifiers to the right of this modifier, or modifiers that are children of the layout node that this modifier is attached to.

default final @NonNull Modifier
NestedScrollModifierKt.nestedScroll(
    @NonNull Modifier receiver,
    @NonNull NestedScrollConnection connection,
    NestedScrollDispatcher dispatcher
)

Modify element to make it participate in the nested scrolling hierarchy.

default final @NonNull Modifier

Offset the content by offset px.

default final @NonNull Modifier
OffsetKt.absoluteOffset(
    @NonNull Modifier receiver,
    @NonNull Dp x,
    @NonNull Dp y
)

Offset the content by (x dp, y dp).

default final @NonNull Modifier
OffsetKt.offset(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull IntOffset> offset
)

Offset the content by offset px.

default final @NonNull Modifier

Offset the content by (x dp, y dp).

default final @NonNull Modifier
OnGloballyPositionedModifierKt.onGloballyPositioned(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinatesUnit> onGloballyPositioned
)

Invoke onGloballyPositioned with the LayoutCoordinates of the element when the global position of the content may have changed.

default final @NonNull Modifier
OnPlacedModifierKt.onPlaced(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinatesUnit> onPlaced
)

Invoke onPlaced after the parent LayoutModifier and parent layout has been placed and before child LayoutModifier is placed.

default final @NonNull Modifier
OnRemeasuredModifierKt.onSizeChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull IntSizeUnit> onSizeChanged
)

Invoked with the size of the modified Compose UI element when the element is first measured or when the size of the element changes.

default final @NonNull Modifier

Renders overscroll from the provided overscrollEffect.

default final @NonNull Modifier
PaddingKt.absolutePadding(
    @NonNull Modifier receiver,
    @NonNull Dp left,
    @NonNull Dp top,
    @NonNull Dp right,
    @NonNull Dp bottom
)

Apply additional space along each edge of the content in Dp: left, top, right and bottom.

default final @NonNull Modifier

Apply all dp of additional space along each edge of the content, left, top, right and bottom.

default final @NonNull Modifier
PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull PaddingValues paddingValues
)

Apply PaddingValues to the component as additional space along each edge of the content's left, top, right and bottom.

default final @NonNull Modifier
PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull Dp horizontal,
    @NonNull Dp vertical
)

Apply horizontal dp space along the left and right edges of the content, and vertical dp space along the top and bottom edges.

default final @NonNull Modifier
PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull Dp start,
    @NonNull Dp top,
    @NonNull Dp end,
    @NonNull Dp bottom
)

Apply additional space along each edge of the content in Dp: start, top, end and bottom.

default final @NonNull Modifier
PainterModifierKt.paint(
    @NonNull Modifier receiver,
    @NonNull Painter painter,
    boolean sizeToIntrinsics,
    @NonNull Alignment alignment,
    @NonNull ContentScale contentScale,
    float alpha,
    ColorFilter colorFilter
)

Paint the content using painter.

default final @NonNull Modifier
PointerIconKt.pointerHoverIcon(
    @NonNull Modifier receiver,
    @NonNull PointerIcon icon,
    boolean overrideDescendants
)

Modifier that lets a developer define a pointer icon to display when the cursor is hovered over the element.

default final @NonNull Modifier
PointerInteropFilterKt.motionEventSpy(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull MotionEventUnit> watcher
)

Calls watcher with each MotionEvent that the layout area or any child pointerInput receives.

default final @NonNull Modifier
@ExperimentalComposeUiApi
PointerInteropFilterKt.pointerInteropFilter(
    @NonNull Modifier receiver,
    RequestDisallowInterceptTouchEvent requestDisallowInterceptTouchEvent,
    @NonNull Function1<@NonNull MotionEvent, @NonNull Boolean> onTouchEvent
)

A special PointerInputModifier that provides access to the underlying MotionEvents originally dispatched to Compose.

default final @NonNull Modifier

Contains the semantics required for an indeterminate progress indicator, that represents the fact of the in-progress operation.

default final @NonNull Modifier
ProgressSemanticsKt.progressSemantics(
    @NonNull Modifier receiver,
    float value,
    @NonNull ClosedFloatingPointRange<@NonNull Float> valueRange,
    int steps
)

Contains the semantics required for a determinate progress indicator or the progress part of a slider, that represents progress within valueRange.

default final @NonNull Modifier

This method is deprecated. Please use bringIntoViewRequester instead.

default final @NonNull Modifier
RotaryInputModifierKt.onPreRotaryScrollEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onPreRotaryScrollEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept RotaryScrollEvents if it (or one of its children) is focused.

default final @NonNull Modifier
RotaryInputModifierKt.onRotaryScrollEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onRotaryScrollEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept RotaryScrollEvents if it (or one of its children) is focused.

default final @NonNull Modifier
RotateKt.rotate(@NonNull Modifier receiver, float degrees)

Sets the degrees the view is rotated around the center of the composable.

default final @NonNull Modifier
ScaleKt.scale(@NonNull Modifier receiver, float scale)

Scale the contents of both the horizontal and vertical axis uniformly by the same scale factor.

default final @NonNull Modifier
ScaleKt.scale(@NonNull Modifier receiver, float scaleX, float scaleY)

Scale the contents of the composable by the following scale factors along the horizontal and vertical axis respectively.

default final @NonNull Modifier
ScrollKt.horizontalScroll(
    @NonNull Modifier receiver,
    @NonNull ScrollState state,
    boolean enabled,
    FlingBehavior flingBehavior,
    boolean reverseScrolling
)

Modify element to allow to scroll horizontally when width of the content is bigger than max constraints allow.

default final @NonNull Modifier
ScrollKt.verticalScroll(
    @NonNull Modifier receiver,
    @NonNull ScrollState state,
    boolean enabled,
    FlingBehavior flingBehavior,
    boolean reverseScrolling
)

Modify element to allow to scroll vertically when height of the content is bigger than max constraints allow.

default final @NonNull Modifier
ScrollableKt.scrollable(
    @NonNull Modifier receiver,
    @NonNull ScrollableState state,
    @NonNull Orientation orientation,
    boolean enabled,
    boolean reverseDirection,
    FlingBehavior flingBehavior,
    MutableInteractionSource interactionSource
)

Configure touch scrolling and flinging for the UI element in a single Orientation.

default final @NonNull Modifier
@ExperimentalFoundationApi
ScrollableKt.scrollable(
    @NonNull Modifier receiver,
    @NonNull ScrollableState state,
    @NonNull Orientation orientation,
    OverscrollEffect overscrollEffect,
    boolean enabled,
    boolean reverseDirection,
    FlingBehavior flingBehavior,
    MutableInteractionSource interactionSource
)

Configure touch scrolling and flinging for the UI element in a single Orientation.

default final @NonNull Modifier

Use this modifier to group a list of selectable items like Tabs or RadioButtons together for accessibility purpose.

default final @NonNull Modifier
SelectableKt.selectable(
    @NonNull Modifier receiver,
    boolean selected,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to be selectable, usually as a part of a mutually exclusive group, where only one item can be selected at any point in time.

default final @NonNull Modifier
SelectableKt.selectable(
    @NonNull Modifier receiver,
    boolean selected,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to be selectable, usually as a part of a mutually exclusive group, where only one item can be selected at any point in time.

default final @NonNull Modifier

Clears the semantics of all the descendant nodes and sets new semantics.

default final @NonNull Modifier
SemanticsModifierKt.semantics(
    @NonNull Modifier receiver,
    boolean mergeDescendants,
    @ExtensionFunctionType @NonNull Function1<@NonNull SemanticsPropertyReceiverUnit> properties
)

Add semantics key/value pairs to the layout node, for use in testing, accessibility, etc.

default final @NonNull Modifier
ShadowKt.shadow(
    @NonNull Modifier receiver,
    @NonNull Dp elevation,
    @NonNull Shape shape,
    boolean clip,
    @NonNull Color ambientColor,
    @NonNull Color spotColor
)

Creates a graphicsLayer that draws a shadow.

default final @NonNull Modifier
SizeKt.defaultMinSize(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight
)

Constrain the size of the wrapped layout only when it would be otherwise unconstrained: the minWidth and minHeight constraints are only applied when the incoming corresponding constraint is 0.

default final @NonNull Modifier
SizeKt.fillMaxHeight(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxHeight of the incoming measurement constraints, by setting the minimum height and the maximum height to be equal to the maximum height multiplied by fraction.

default final @NonNull Modifier
SizeKt.fillMaxSize(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxWidth and Constraints.maxHeight of the incoming measurement constraints, by setting the minimum width and the maximum width to be equal to the maximum width multiplied by fraction, as well as the minimum height and the maximum height to be equal to the maximum height multiplied by fraction.

default final @NonNull Modifier
SizeKt.fillMaxWidth(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxWidth of the incoming measurement constraints, by setting the minimum width and the maximum width to be equal to the maximum width multiplied by fraction.

default final @NonNull Modifier
SizeKt.height(@NonNull Modifier receiver, @NonNull Dp height)

Declare the preferred height of the content to be exactly heightdp.

default final @NonNull Modifier
SizeKt.heightIn(@NonNull Modifier receiver, @NonNull Dp min, @NonNull Dp max)

Constrain the height of the content to be between mindp and maxdp as permitted by the incoming measurement Constraints.

default final @NonNull Modifier

Declare the height of the content to be exactly heightdp.

default final @NonNull Modifier
SizeKt.requiredHeightIn(
    @NonNull Modifier receiver,
    @NonNull Dp min,
    @NonNull Dp max
)

Constrain the height of the content to be between mindp and maxdp.

default final @NonNull Modifier

Declare the size of the content to be exactly sizedp width and height.

default final @NonNull Modifier

Declare the size of the content to be exactly size.

default final @NonNull Modifier
SizeKt.requiredSize(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Dp height
)

Declare the size of the content to be exactly widthdp and heightdp.

default final @NonNull Modifier
SizeKt.requiredSizeIn(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight,
    @NonNull Dp maxWidth,
    @NonNull Dp maxHeight
)

Constrain the width of the content to be between minWidthdp and maxWidthdp, and the height of the content to be between minHeightdp and maxHeightdp.

default final @NonNull Modifier

Declare the width of the content to be exactly widthdp.

default final @NonNull Modifier
SizeKt.requiredWidthIn(
    @NonNull Modifier receiver,
    @NonNull Dp min,
    @NonNull Dp max
)

Constrain the width of the content to be between mindp and maxdp.

default final @NonNull Modifier
SizeKt.size(@NonNull Modifier receiver, @NonNull Dp size)

Declare the preferred size of the content to be exactly sizedp square.

default final @NonNull Modifier
SizeKt.size(@NonNull Modifier receiver, @NonNull DpSize size)

Declare the preferred size of the content to be exactly size.

default final @NonNull Modifier
SizeKt.size(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Dp height
)

Declare the preferred size of the content to be exactly widthdp by heightdp.

default final @NonNull Modifier
SizeKt.sizeIn(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight,
    @NonNull Dp maxWidth,
    @NonNull Dp maxHeight
)

Constrain the width of the content to be between minWidthdp and maxWidthdp and the height of the content to be between minHeightdp and maxHeightdp as permitted by the incoming measurement Constraints.

default final @NonNull Modifier
SizeKt.width(@NonNull Modifier receiver, @NonNull Dp width)

Declare the preferred width of the content to be exactly widthdp.

default final @NonNull Modifier
SizeKt.widthIn(@NonNull Modifier receiver, @NonNull Dp min, @NonNull Dp max)

Constrain the width of the content to be between mindp and maxdp as permitted by the incoming measurement Constraints.

default final @NonNull Modifier
SizeKt.wrapContentHeight(
    @NonNull Modifier receiver,
    @NonNull Alignment.Vertical align,
    boolean unbounded
)

Allow the content to measure at its desired height without regard for the incoming measurement minimum height constraint, and, if unbounded is true, also without regard for the incoming measurement maximum height constraint.

default final @NonNull Modifier
SizeKt.wrapContentSize(
    @NonNull Modifier receiver,
    @NonNull Alignment align,
    boolean unbounded
)

Allow the content to measure at its desired size without regard for the incoming measurement minimum width or minimum height constraints, and, if unbounded is true, also without regard for the incoming maximum constraints.

default final @NonNull Modifier
SizeKt.wrapContentWidth(
    @NonNull Modifier receiver,
    @NonNull Alignment.Horizontal align,
    boolean unbounded
)

Allow the content to measure at its desired width without regard for the incoming measurement minimum width constraint, and, if unbounded is true, also without regard for the incoming measurement maximum width constraint.

default final @NonNull Modifier

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events before they are sent to the software keyboard.

default final @NonNull Modifier

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events before they are sent to the software keyboard.

default final @NonNull Modifier

Excludes the layout rectangle from the system gesture.

default final @NonNull Modifier

Excludes a rectangle within the local layout coordinates from the system gesture.

default final @NonNull Modifier

Applies a tag to allow modified element to be found in tests.

default final @NonNull Modifier
ToggleableKt.toggleable(
    @NonNull Modifier receiver,
    boolean value,
    boolean enabled,
    Role role,
    @NonNull Function1<@NonNull BooleanUnit> onValueChange
)

Configure component to make it toggleable via input and accessibility events

default final @NonNull Modifier
ToggleableKt.toggleable(
    @NonNull Modifier receiver,
    boolean value,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function1<@NonNull BooleanUnit> onValueChange
)

Configure component to make it toggleable via input and accessibility events.

default final @NonNull Modifier
ToggleableKt.triStateToggleable(
    @NonNull Modifier receiver,
    @NonNull ToggleableState state,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to make it toggleable via input and accessibility events with three states: On, Off and Indeterminate.

default final @NonNull Modifier
ToggleableKt.triStateToggleable(
    @NonNull Modifier receiver,
    @NonNull ToggleableState state,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to make it toggleable via input and accessibility events with three states: On, Off and Indeterminate.

default final @NonNull Modifier
TransformableKt.transformable(
    @NonNull Modifier receiver,
    @NonNull TransformableState state,
    boolean lockRotationOnZoomPan,
    boolean enabled
)

Enable transformation gestures of the modified UI element.

default final @NonNull Modifier
@ExperimentalFoundationApi
TransformableKt.transformable(
    @NonNull Modifier receiver,
    @NonNull TransformableState state,
    @NonNull Function0<@NonNull Boolean> canPan,
    boolean lockRotationOnZoomPan,
    boolean enabled
)

Enable transformation gestures of the modified UI element.

default final @NonNull Modifier

Controls the soft keyboard as a nested scrolling on Android R and later.

default final @NonNull Modifier

Adds padding to accommodate the caption bar insets.

default final @NonNull Modifier

Consume insets that haven't been consumed yet by other insets Modifiers similar to windowInsetsPadding without adding any padding.

default final @NonNull Modifier

Consume paddingValues as insets as if the padding was added irrespective of insets.

default final @NonNull Modifier

This method is deprecated. Use consumeWindowInsets

default final @NonNull Modifier

This method is deprecated. Use consumeWindowInsets

default final @NonNull Modifier

Adds padding to accommodate the display cutout.

default final @NonNull Modifier

Adds padding to accommodate the ime insets.

default final @NonNull Modifier

Adds padding to accommodate the mandatory system gestures insets.

default final @NonNull Modifier

Adds padding to accommodate the navigation bars insets.

default final @NonNull Modifier

Calls block with the WindowInsets that have been consumed, either by consumeWindowInsets or one of the padding Modifiers, such as imePadding.

default final @NonNull Modifier

Adds padding to accommodate the safe content insets.

default final @NonNull Modifier

Adds padding to accommodate the safe drawing insets.

default final @NonNull Modifier

Adds padding to accommodate the safe gestures insets.

default final @NonNull Modifier

Adds padding to accommodate the status bars insets.

default final @NonNull Modifier

Adds padding to accommodate the system bars insets.

default final @NonNull Modifier

Adds padding to accommodate the system gestures insets.

default final @NonNull Modifier

Adds padding to accommodate the waterfall insets.

default final @NonNull Modifier

Adds padding so that the content doesn't enter insets space.

default final @NonNull Modifier

This method is deprecated. Use onConsumedWindowInsetsChanged

default final @NonNull Modifier

Sets the height to that of insets at the bottom of the screen.

default final @NonNull Modifier

Sets the width to that of insets at the end of the screen, using either left or right, depending on the LayoutDirection.

default final @NonNull Modifier

Sets the width to that of insets at the start of the screen, using either left or right, depending on the LayoutDirection.

default final @NonNull Modifier

Sets the height to that of insets at the top of the screen.

default final @NonNull Modifier
ZIndexModifierKt.zIndex(@NonNull Modifier receiver, float zIndex)

Creates a modifier that controls the drawing order for the children of the same layout parent.

Public methods

all

abstract boolean all(
    @NonNull Function1<@NonNull Modifier.Element, @NonNull Boolean> predicate
)

Returns true if predicate returns true for all Elements in this Modifier or if this Modifier contains no Elements.

any

abstract boolean any(
    @NonNull Function1<@NonNull Modifier.Element, @NonNull Boolean> predicate
)

Returns true if predicate returns true for any Element in this Modifier.

foldIn

abstract @NonNull R <R extends Object> foldIn(
    @NonNull R initial,
    @NonNull Function2<@NonNull R, @NonNull Modifier.Element, @NonNull R> operation
)

Accumulates a value starting with initial and applying operation to the current value and each element from outside in.

Elements wrap one another in a chain from left to right; an Element that appears to the left of another in a + expression or in operation's parameter order affects all of the elements that appear after it. foldIn may be used to accumulate a value starting from the parent or head of the modifier chain to the final wrapped child.

foldOut

abstract @NonNull R <R extends Object> foldOut(
    @NonNull R initial,
    @NonNull Function2<@NonNull Modifier.Element, @NonNull R, @NonNull R> operation
)

Accumulates a value starting with initial and applying operation to the current value and each element from inside out.

Elements wrap one another in a chain from left to right; an Element that appears to the left of another in a + expression or in operation's parameter order affects all of the elements that appear after it. foldOut may be used to accumulate a value starting from the child or tail of the modifier chain up to the parent or head of the chain.

then

default @NonNull Modifier then(@NonNull Modifier other)

Concatenates this modifier with another.

Returns a Modifier representing this modifier followed by other in sequence.

Extension functions

AlignmentLineKt.paddingFrom

default final @NonNull Modifier AlignmentLineKt.paddingFrom(
    @NonNull Modifier receiver,
    @NonNull AlignmentLine alignmentLine,
    @NonNull Dp before,
    @NonNull Dp after
)

A Modifier that can add padding to position the content according to specified distances from its bounds to an alignment line. Whether the positioning is vertical or horizontal is defined by the orientation of the given alignmentLine (if the line is horizontal, before and after will refer to distances from top and bottom, otherwise they will refer to distances from start and end). The opposite axis sizing and positioning will remain unaffected. The modified layout will try to include the required padding, subject to the incoming max layout constraints, such that the distance from its bounds to the alignmentLine of the content will be before and after, respectively. When the max constraints do not allow this, satisfying the before requirement will have priority over after. When the modified layout is min constrained in the affected layout direction and the padded layout is smaller than the constraint, the modified layout will satisfy the min constraint and the content will be positioned to satisfy the before requirement if specified, or the after requirement otherwise.

import androidx.compose.foundation.layout.paddingFrom
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// We want to have 30.sp distance from the top of the layout box to the baseline of the
// first line of text.
val distanceToBaseline = 30.sp
// We convert the 30.sp value to dps, which is required for the paddingFrom API.
val distanceToBaselineDp = with(LocalDensity.current) { distanceToBaseline.toDp() }
// The result will be a layout with 30.sp distance from the top of the layout box to the
// baseline of the first line of text.
Text(
    text = "This is an example.",
    modifier = Modifier.paddingFrom(FirstBaseline, before = distanceToBaselineDp)
)
Parameters
@NonNull AlignmentLine alignmentLine

the alignment line relative to which the padding is defined

@NonNull Dp before

the distance between the container's top edge and the horizontal alignment line, or the container's start edge and the vertical alignment line

@NonNull Dp after

the distance between the container's bottom edge and the horizontal alignment line, or the container's end edge and the vertical alignment line

See also
paddingFromBaseline

Example usage:

AlignmentLineKt.paddingFrom

default final @NonNull Modifier AlignmentLineKt.paddingFrom(
    @NonNull Modifier receiver,
    @NonNull AlignmentLine alignmentLine,
    @NonNull TextUnit before,
    @NonNull TextUnit after
)

A Modifier that can add padding to position the content according to specified distances from its bounds to an alignment line. Whether the positioning is vertical or horizontal is defined by the orientation of the given alignmentLine (if the line is horizontal, before and after will refer to distances from top and bottom, otherwise they will refer to distances from start and end). The opposite axis sizing and positioning will remain unaffected. The modified layout will try to include the required padding, subject to the incoming max layout constraints, such that the distance from its bounds to the alignmentLine of the content will be before and after, respectively. When the max constraints do not allow this, satisfying the before requirement will have priority over after. When the modified layout is min constrained in the affected layout direction and the padded layout is smaller than the constraint, the modified layout will satisfy the min constraint and the content will be positioned to satisfy the before requirement if specified, or the after requirement otherwise.

import androidx.compose.foundation.layout.paddingFrom
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// We want to have 30.sp distance from the top of the layout box to the baseline of the
// first line of text.
val distanceToBaseline = 30.sp
// We convert the 30.sp value to dps, which is required for the paddingFrom API.
val distanceToBaselineDp = with(LocalDensity.current) { distanceToBaseline.toDp() }
// The result will be a layout with 30.sp distance from the top of the layout box to the
// baseline of the first line of text.
Text(
    text = "This is an example.",
    modifier = Modifier.paddingFrom(FirstBaseline, before = distanceToBaselineDp)
)
Parameters
@NonNull AlignmentLine alignmentLine

the alignment line relative to which the padding is defined

@NonNull TextUnit before

the distance between the container's top edge and the horizontal alignment line, or the container's start edge and the vertical alignment line

@NonNull TextUnit after

the distance between the container's bottom edge and the horizontal alignment line, or the container's end edge and the vertical alignment line

See also
paddingFromBaseline

Example usage:

AlignmentLineKt.paddingFromBaseline

default final @NonNull Modifier AlignmentLineKt.paddingFromBaseline(
    @NonNull Modifier receiver,
    @NonNull Dp top,
    @NonNull Dp bottom
)

A Modifier that positions the content in a layout such that the distance from the top of the layout to the baseline of the first line of text in the content is top, and the distance from the baseline of the last line of text in the content to the bottom of the layout is bottom.

When the modified layout is min height constrained and the padded layout is smaller than the constraint, the modified layout will satisfy the min constraint and the content will be positioned to satisfy the top requirement if specified, or the bottom requirement otherwise.

import androidx.compose.foundation.layout.paddingFrom
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// We want to have 30.dp distance from the top of the layout box to the baseline of the
// first line of text, and a 40.dp distance from the bottom of the layout box to the baseline
// of the last line of text. Note it is good practice to specify these distances in sp for font
// scaling, which can be done with the other overload.
val distanceToFirstBaseline = 30.dp
val distanceFromLastBaseline = 40.dp
Text(
    text = "This line has the first baseline.\nThis line has the last baseline.",
    modifier = Modifier.paddingFromBaseline(distanceToFirstBaseline, distanceFromLastBaseline)
)
See also
paddingFrom

Example usage:

AlignmentLineKt.paddingFromBaseline

default final @NonNull Modifier AlignmentLineKt.paddingFromBaseline(
    @NonNull Modifier receiver,
    @NonNull TextUnit top,
    @NonNull TextUnit bottom
)

A Modifier that positions the content in a layout such that the distance from the top of the layout to the baseline of the first line of text in the content is top, and the distance from the baseline of the last line of text in the content to the bottom of the layout is bottom.

When the modified layout is min height constrained and the padded layout is smaller than the constraint, the modified layout will satisfy the min constraint and the content will be positioned to satisfy the top requirement if specified, or the bottom requirement otherwise.

import androidx.compose.foundation.layout.paddingFrom
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.unit.sp

// We want to have 30.sp distance from the top of the layout box to the baseline of the
// first line of text, and a 40.sp distance from the bottom of the layout box to the baseline
// of the last line of text.
val distanceToFirstBaseline = 30.sp
val distanceFromLastBaseline = 40.sp
Text(
    text = "This line has the first baseline.\nThis line has the last baseline.",
    modifier = Modifier.paddingFromBaseline(distanceToFirstBaseline, distanceFromLastBaseline)
)
See also
paddingFrom

Example usage:

AlphaKt.alpha

default final @NonNull Modifier AlphaKt.alpha(@NonNull Modifier receiver, float alpha)

Draw content with modified alpha that may be less than 1.

Usage of this API renders this composable into a separate graphics layer. Note when an alpha less than 1.0f is provided, contents are implicitly clipped to their bounds. This is because an intermediate compositing layer is created to render contents into first before being drawn into the destination with the desired alpha. This layer is sized to the bounds of the composable this modifier is configured on, and contents outside of these bounds are omitted.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.size(100.dp).alpha(alpha = 0.5f).background(Color.Red))
Parameters
float alpha

the fraction of children's alpha value and must be between 0 and 1, inclusive.

See also
graphicsLayer

Example usage:

AnimationModifierKt.animateContentSize

default final @NonNull Modifier AnimationModifierKt.animateContentSize(
    @NonNull Modifier receiver,
    @NonNull FiniteAnimationSpec<@NonNull IntSize> animationSpec,
    Function2<@NonNull IntSize, @NonNull IntSizeUnit> finishedListener
)

This modifier animates its own size when its child modifier (or the child composable if it is already at the tail of the chain) changes size. This allows the parent modifier to observe a smooth size change, resulting in an overall continuous visual change.

A FiniteAnimationSpec can be optionally specified for the size change animation. By default, spring will be used.

An optional finishedListener can be supplied to get notified when the size change animation is finished. Since the content size change can be dynamic in many cases, both initial value and target value (i.e. final size) will be passed to the finishedListener. Note: if the animation is interrupted, the initial value will be the size at the point of interruption. This is intended to help determine the direction of the size change (i.e. expand or collapse in x and y dimensions).

import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LocalTextStyle
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val shortText = "Hi"
val longText = "Very long text\nthat spans across\nmultiple lines"
var short by remember { mutableStateOf(true) }
Box(
    modifier = Modifier
        .background(
            Color.Blue,
            RoundedCornerShape(15.dp)
        )
        .clickable { short = !short }
        .padding(20.dp)
        .wrapContentSize()
        .animateContentSize()
) {
    Text(
        if (short) {
            shortText
        } else {
            longText
        },
        style = LocalTextStyle.current.copy(color = Color.White)
    )
}
Parameters
@NonNull FiniteAnimationSpec<@NonNull IntSize> animationSpec

a finite animation that will be used to animate size change, spring by default

Function2<@NonNull IntSize, @NonNull IntSizeUnit> finishedListener

an optional listener to be called when the content change animation is completed.

AspectRatioKt.aspectRatio

default final @NonNull Modifier AspectRatioKt.aspectRatio(
    @NonNull Modifier receiver,
    float ratio,
    boolean matchHeightConstraintsFirst
)

Attempts to size the content to match a specified aspect ratio by trying to match one of the incoming constraints in the following order: Constraints.maxWidth, Constraints.maxHeight, Constraints.minWidth, Constraints.minHeight if matchHeightConstraintsFirst is false (which is the default), or Constraints.maxHeight, Constraints.maxWidth, Constraints.minHeight, Constraints.minWidth if matchHeightConstraintsFirst is true. The size in the other dimension is determined by the aspect ratio. The combinations will be tried in this order until one non-empty is found to satisfy the constraints. If no valid size is obtained this way, it means that there is no non-empty size satisfying both the constraints and the aspect ratio, so the constraints will not be respected and the content will be sized such that the Constraints.maxWidth or Constraints.maxHeight is matched (depending on matchHeightConstraintsFirst).

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.width(100.dp).aspectRatio(2f).background(Color.Green))
Parameters
float ratio

the desired width/height positive ratio

BackgroundKt.background

default final @NonNull Modifier BackgroundKt.background(
    @NonNull Modifier receiver,
    @NonNull Color color,
    @NonNull Shape shape
)

Draws shape with a solid color behind the content.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Text(
    "Text with background",
    Modifier.background(color = Color.Magenta).padding(10.dp)
)
Parameters
@NonNull Color color

color to paint background with

@NonNull Shape shape

desired shape of the background

BackgroundKt.background

default final @NonNull Modifier BackgroundKt.background(
    @NonNull Modifier receiver,
    @NonNull Brush brush,
    @NonNull Shape shape,
    float alpha
)

Draws shape with brush behind the content.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val gradientBrush = Brush.horizontalGradient(
    colors = listOf(Color.Red, Color.Blue, Color.Green),
    startX = 0.0f,
    endX = 500.0f
)
Text(
    "Text with gradient back",
    Modifier.background(brush = gradientBrush, shape = CutCornerShape(8.dp))
        .padding(10.dp)
)
Parameters
@NonNull Brush brush

brush to paint background with

@NonNull Shape shape

desired shape of the background

float alpha

Opacity to be applied to the brush, with 0 being completely transparent and 1 being completely opaque. The value must be between 0 and 1.

BasicMarqueeKt.basicMarquee

@ExperimentalFoundationApi
default final @NonNull Modifier BasicMarqueeKt.basicMarquee(
    @NonNull Modifier receiver,
    int iterations,
    @NonNull MarqueeAnimationMode animationMode,
    int delayMillis,
    int initialDelayMillis,
    @NonNull MarqueeSpacing spacing,
    @NonNull Dp velocity
)

Applies an animated marquee effect to the modified content if it's too wide to fit in the available space. This modifier has no effect if the content fits in the max constraints. The content will be measured with unbounded width.

When the animation is running, it will restart from the initial state any time:

The animation only affects the drawing of the content, not its position. The offset returned by the LayoutCoordinates of anything inside the marquee is undefined relative to anything outside the marquee, and may not match its drawn position on screen. This modifier also does not currently support content that accepts position-based input such as pointer events.

import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

// Marquee only animates when the content doesn't fit in the max width.
Column(Modifier.width(30.dp)) {
    Text("hello world", Modifier.basicMarquee())
}

To only animate when the composable is focused, specify animationMode and make the composable focusable.

import androidx.compose.foundation.MarqueeAnimationMode
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.unit.dp

val focusRequester = remember { FocusRequester() }

// Marquee only animates when the content doesn't fit in the max width.
Column(Modifier.width(30.dp)) {
    Text("hello world", Modifier
        .clickable { focusRequester.requestFocus() }
        .basicMarquee(animationMode = MarqueeAnimationMode.WhileFocused)
        .focusRequester(focusRequester)
        .focusable()
    )
}

This modifier does not add any visual effects aside from scrolling, but you can add your own by placing modifiers before this one.

import androidx.compose.foundation.MarqueeSpacing
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp

val edgeWidth = 32.dp
fun ContentDrawScope.drawFadedEdge(leftEdge: Boolean) {
    val edgeWidthPx = edgeWidth.toPx()
    drawRect(
        topLeft = Offset(if (leftEdge) 0f else size.width - edgeWidthPx, 0f),
        size = Size(edgeWidthPx, size.height),
        brush = Brush.horizontalGradient(
            colors = listOf(Color.Transparent, Color.Black),
            startX = if (leftEdge) 0f else size.width,
            endX = if (leftEdge) edgeWidthPx else size.width - edgeWidthPx
        ),
        blendMode = BlendMode.DstIn
    )
}

Text(
    "the quick brown fox jumped over the lazy dogs",
    Modifier
        .widthIn(max = edgeWidth * 4)
        // Rendering to an offscreen buffer is required to get the faded edges' alpha to be
        // applied only to the text, and not whatever is drawn below this composable (e.g. the
        // window).
        .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
        .drawWithContent {
            drawContent()
            drawFadedEdge(leftEdge = true)
            drawFadedEdge(leftEdge = false)
        }
        .basicMarquee(
            // Animate forever.
            iterations = Int.MAX_VALUE,
            spacing = MarqueeSpacing(0.dp)
        )
        .padding(start = edgeWidth)
)
Parameters
int iterations

The number of times to repeat the animation. Int.MAX_VALUE will repeat forever, and 0 will disable animation.

@NonNull MarqueeAnimationMode animationMode

Whether the marquee should start animating Immediately or only WhileFocused. In WhileFocused mode, the modified node or the content must be made focusable. Note that the initialDelayMillis is part of the animation, so this parameter determines when that initial delay starts counting down, not when the content starts to actually scroll.

int delayMillis

The duration to wait before starting each subsequent iteration, in millis.

int initialDelayMillis

The duration to wait before starting the first iteration of the animation, in millis. By default, there will be no initial delay if animationMode is WhileFocused, otherwise the initial delay will be delayMillis.

@NonNull MarqueeSpacing spacing

A MarqueeSpacing that specifies how much space to leave at the end of the content before showing the beginning again.

@NonNull Dp velocity

The speed of the animation in dps / second.

BlurKt.blur

default final @NonNull Modifier BlurKt.blur(
    @NonNull Modifier receiver,
    @NonNull Dp radius,
    @NonNull BlurredEdgeTreatment edgeTreatment
)

Draw content blurred with the specified radii. Note this effect is only supported on Android 12 and above. Attempts to use this Modifier on older Android versions will be ignored.

Usage of this API renders the corresponding composable into a separate graphics layer. Because the blurred content renders a larger area by the blur radius, this layer is explicitly clipped to the content bounds. It is recommended introduce additional space around the drawn content by the specified blur radius to remain within the content bounds.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(
    Modifier.size(300.dp)
        // Blur content allowing the result to extend beyond the bounds of the original content
        .blur(
            30.dp,
            edgeTreatment = BlurredEdgeTreatment.Unbounded
        )
        .background(Color.Red, CircleShape)
)
import androidx.compose.foundation.Image
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

Image(
    painter = painterResource(R.drawable.circus),
    contentDescription = "sample blurred image",
    // Blur content within the original bounds, clipping the result to a rounded rectangle
    modifier = Modifier.blur(30.dp, BlurredEdgeTreatment(RoundedCornerShape(5.dp)))
)
Parameters
@NonNull Dp radius

Radius of the blur along both the x and y axis

@NonNull BlurredEdgeTreatment edgeTreatment

Strategy used to render pixels outside of bounds of the original input

See also
graphicsLayer

Example usage:

BlurKt.blur

default final @NonNull Modifier BlurKt.blur(
    @NonNull Modifier receiver,
    @NonNull Dp radiusX,
    @NonNull Dp radiusY,
    @NonNull BlurredEdgeTreatment edgeTreatment
)

Draw content blurred with the specified radii. Note this effect is only supported on Android 12 and above. Attempts to use this Modifier on older Android versions will be ignored.

Usage of this API renders the corresponding composable into a separate graphics layer. Because the blurred content renders a larger area by the blur radius, this layer is explicitly clipped to the content bounds. It is recommended introduce additional space around the drawn content by the specified blur radius to remain within the content bounds.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(
    Modifier.size(300.dp)
        // Blur content allowing the result to extend beyond the bounds of the original content
        .blur(
            30.dp,
            edgeTreatment = BlurredEdgeTreatment.Unbounded
        )
        .background(Color.Red, CircleShape)
)
import androidx.compose.foundation.Image
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

Image(
    painter = painterResource(R.drawable.circus),
    contentDescription = "sample blurred image",
    // Blur content within the original bounds, clipping the result to a rounded rectangle
    modifier = Modifier.blur(30.dp, BlurredEdgeTreatment(RoundedCornerShape(5.dp)))
)
Parameters
@NonNull Dp radiusX

Radius of the blur along the x axis

@NonNull Dp radiusY

Radius of the blur along the y axis

@NonNull BlurredEdgeTreatment edgeTreatment

Strategy used to render pixels outside of bounds of the original input

See also
graphicsLayer

Example usage:

BorderKt.border

default final @NonNull Modifier BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull BorderStroke border,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a border and a shape and clip it.

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Text(
    "Text with  square border",
    modifier = Modifier
        .border(4.dp, Color.Magenta)
        .padding(10.dp)
)

()

Parameters
@NonNull BorderStroke border

BorderStroke class that specifies border appearance, such as size and color

@NonNull Shape shape

shape of the border

BorderKt.border

default final @NonNull Modifier BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Brush brush,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a width, a brush and a shape and clip it.

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.dp

val gradientBrush = Brush.horizontalGradient(
    colors = listOf(Color.Red, Color.Blue, Color.Green),
    startX = 0.0f,
    endX = 500.0f,
    tileMode = TileMode.Repeated
)
Text(
    "Text with gradient border",
    modifier = Modifier
        .border(width = 2.dp, brush = gradientBrush, shape = CircleShape)
        .padding(10.dp)
)

()

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

val widthRange = (1..10)
var width by remember { mutableStateOf((widthRange.random()).dp) }

val shapes = remember {
    listOf(CutCornerShape(8.dp), CircleShape, RoundedCornerShape(20))
}
var selectedShape by remember { mutableStateOf(shapes.random()) }

val colors = listOf(
    Color.Black,
    Color.DarkGray,
    Color.Gray,
    Color.LightGray,
    Color.White,
    Color.Red,
    Color.Blue,
    Color.Green,
    Color.Yellow,
    Color.Cyan,
    Color.Magenta
)
var gradientBrush by remember {
    mutableStateOf(
        Brush.horizontalGradient(
            colors = listOf(colors.random(), colors.random(), colors.random()),
            startX = 0.0f,
            endX = 500.0f,
            tileMode = TileMode.Repeated
        )
    )
}

Column(Modifier.padding(2.dp)) {
    Text(text = "Update border with buttons")
    Row {
        Button(
            modifier = Modifier.width(60.dp),
            onClick = {

                width = (widthRange.random()).dp
            }
        ) {
            Text(
                fontSize = 8.sp,
                text = "width"
            )
        }
        Button(
            modifier = Modifier.width(60.dp),
            onClick = {
                gradientBrush = Brush.horizontalGradient(
                    colors = listOf(colors.random(), colors.random(), colors.random()),
                    startX = 0.0f,
                    endX = 500.0f,
                    tileMode = TileMode.Repeated
                )
            }
        ) {
            Text(
                fontSize = 8.sp,
                text = "brush"
            )
        }
        Button(
            modifier = Modifier.width(60.dp),
            onClick = {
                selectedShape = shapes.random()
            }
        ) {
            Text(
                fontSize = 8.sp,
                text = "shape"
            )
        }
    }
    Text(
        "Dynamic border",
        modifier = Modifier
            .border(
                width = width,
                brush = gradientBrush,
                shape = selectedShape
            )
            .padding(10.dp)
    )
}

()

Parameters
@NonNull Dp width

width of the border. Use Dp.Hairline for a hairline border.

@NonNull Brush brush

brush to paint the border with

@NonNull Shape shape

shape of the border

BorderKt.border

default final @NonNull Modifier BorderKt.border(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Color color,
    @NonNull Shape shape
)

Modify element to add border with appearance specified with a width, a color and a shape and clip it.

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CutCornerShape
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Text(
    "Text with gradient border",
    modifier = Modifier
        .border(
            border = BorderStroke(2.dp, Color.Blue),
            shape = CutCornerShape(8.dp)
        )
        .padding(10.dp)
)

()

Parameters
@NonNull Dp width

width of the border. Use Dp.Hairline for a hairline border.

@NonNull Color color

color to paint the border with

@NonNull Shape shape

shape of the border

BringIntoViewRequesterKt.bringIntoViewRequester

@ExperimentalFoundationApi
default final @NonNull Modifier BringIntoViewRequesterKt.bringIntoViewRequester(
    @NonNull Modifier receiver,
    @NonNull BringIntoViewRequester bringIntoViewRequester
)

Modifier that can be used to send bringIntoView requests.

The following example uses a bringIntoViewRequester to bring an item into the parent bounds. The example demonstrates how a composable can ask its parents to scroll so that the component using this modifier is brought into the bounds of all its parents.

import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.focus.onFocusChanged

Row(Modifier.horizontalScroll(rememberScrollState())) {
    repeat(100) {
        val bringIntoViewRequester = remember { BringIntoViewRequester() }
        val coroutineScope = rememberCoroutineScope()
        Box(
            Modifier
                // This associates the RelocationRequester with a Composable that wants to be
                // brought into view.
                .bringIntoViewRequester(bringIntoViewRequester)
                .onFocusChanged {
                    if (it.isFocused) {
                        coroutineScope.launch {
                            // This sends a request to all parents that asks them to scroll so
                            // that this item is brought into view.
                            bringIntoViewRequester.bringIntoView()
                        }
                    }
                }
                .focusTarget()
        )
    }
}
Parameters
@NonNull BringIntoViewRequester bringIntoViewRequester

An instance of BringIntoViewRequester. This hoisted object can be used to send bringIntoView requests to parents of the current composable.

BringIntoViewResponderKt.bringIntoViewResponder

@ExperimentalFoundationApi
default final @NonNull Modifier BringIntoViewResponderKt.bringIntoViewResponder(
    @NonNull Modifier receiver,
    @NonNull BringIntoViewResponder responder
)

A parent that can respond to BringIntoViewRequester requests from its children, and scroll so that the item is visible on screen. See BringIntoViewResponder for more details about how this mechanism works.

import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.focus.onFocusChanged

Row(Modifier.horizontalScroll(rememberScrollState())) {
    repeat(100) {
        val bringIntoViewRequester = remember { BringIntoViewRequester() }
        val coroutineScope = rememberCoroutineScope()
        Box(
            Modifier
                // This associates the RelocationRequester with a Composable that wants to be
                // brought into view.
                .bringIntoViewRequester(bringIntoViewRequester)
                .onFocusChanged {
                    if (it.isFocused) {
                        coroutineScope.launch {
                            // This sends a request to all parents that asks them to scroll so
                            // that this item is brought into view.
                            bringIntoViewRequester.bringIntoView()
                        }
                    }
                }
                .focusTarget()
        )
    }
}

ClickableKt.clickable

default final @NonNull Modifier ClickableKt.clickable(
    @NonNull Modifier receiver,
    boolean enabled,
    String onClickLabel,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks via input or accessibility "click" event.

Add this modifier to the element to make it clickable within its bounds and show a default indication when it's pressed.

This version has no MutableInteractionSource or Indication parameters, default indication from LocalIndication will be used. To specify MutableInteractionSource or Indication, use another overload.

If you need to support double click or long click alongside the single click, consider using combinedClickable.

import androidx.compose.foundation.clickable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(text = count.value.toString(), modifier = Modifier.clickable { count.value += 1 })
Parameters
boolean enabled

Controls the enabled state. When false, onClick, and this modifier will appear disabled for accessibility services

String onClickLabel

semantic / accessibility label for the onClick action

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

will be called when user clicks on the element

ClickableKt.clickable

default final @NonNull Modifier ClickableKt.clickable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    String onClickLabel,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks via input or accessibility "click" event.

Add this modifier to the element to make it clickable within its bounds and show an indication as specified in indication parameter.

If you need to support double click or long click alongside the single click, consider using combinedClickable.

import androidx.compose.foundation.clickable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(text = count.value.toString(), modifier = Modifier.clickable { count.value += 1 })
Parameters
@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to dispatch PressInteraction.Press when this clickable is pressed. Only the initial (first) press will be recorded and dispatched with MutableInteractionSource.

Indication indication

indication to be shown when modified element is pressed. By default, indication from LocalIndication will be used. Pass null to show no indication, or current value from LocalIndication to show theme default

boolean enabled

Controls the enabled state. When false, onClick, and this modifier will appear disabled for accessibility services

String onClickLabel

semantic / accessibility label for the onClick action

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

will be called when user clicks on the element

ClickableKt.combinedClickable

@ExperimentalFoundationApi
default final @NonNull Modifier ClickableKt.combinedClickable(
    @NonNull Modifier receiver,
    boolean enabled,
    String onClickLabel,
    Role role,
    String onLongClickLabel,
    Function0<Unit> onLongClick,
    Function0<Unit> onDoubleClick,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks, double clicks and long clicks via input or accessibility "click" event.

Add this modifier to the element to make it clickable within its bounds.

If you need only click handling, and no double or long clicks, consider using clickable

This version has no MutableInteractionSource or Indication parameters, default indication from LocalIndication will be used. To specify MutableInteractionSource or Indication, use another overload.

import androidx.compose.foundation.clickable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(text = count.value.toString(), modifier = Modifier.clickable { count.value += 1 })
Parameters
boolean enabled

Controls the enabled state. When false, onClick, onLongClick or onDoubleClick won't be invoked

String onClickLabel

semantic / accessibility label for the onClick action

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

String onLongClickLabel

semantic / accessibility label for the onLongClick action

Function0<Unit> onLongClick

will be called when user long presses on the element

Function0<Unit> onDoubleClick

will be called when user double clicks on the element

@NonNull Function0<Unit> onClick

will be called when user clicks on the element

ClickableKt.combinedClickable

@ExperimentalFoundationApi
default final @NonNull Modifier ClickableKt.combinedClickable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    String onClickLabel,
    Role role,
    String onLongClickLabel,
    Function0<Unit> onLongClick,
    Function0<Unit> onDoubleClick,
    @NonNull Function0<Unit> onClick
)

Configure component to receive clicks, double clicks and long clicks via input or accessibility "click" event.

Add this modifier to the element to make it clickable within its bounds.

If you need only click handling, and no double or long clicks, consider using clickable.

Add this modifier to the element to make it clickable within its bounds.

import androidx.compose.foundation.clickable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

val count = remember { mutableStateOf(0) }
// content that you want to make clickable
Text(text = count.value.toString(), modifier = Modifier.clickable { count.value += 1 })
Parameters
@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit PressInteraction.Press when this clickable is pressed. Only the initial (first) press will be recorded and emitted with MutableInteractionSource.

Indication indication

indication to be shown when modified element is pressed. By default, indication from LocalIndication will be used. Pass null to show no indication, or current value from LocalIndication to show theme default

boolean enabled

Controls the enabled state. When false, onClick, onLongClick or onDoubleClick won't be invoked

String onClickLabel

semantic / accessibility label for the onClick action

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

String onLongClickLabel

semantic / accessibility label for the onLongClick action

Function0<Unit> onLongClick

will be called when user long presses on the element

Function0<Unit> onDoubleClick

will be called when user double clicks on the element

@NonNull Function0<Unit> onClick

will be called when user clicks on the element

ClipKt.clip

default final @NonNull Modifier ClipKt.clip(@NonNull Modifier receiver, @NonNull Shape shape)

Clip the content to shape.

Parameters
@NonNull Shape shape

the content will be clipped to this Shape.

ClipKt.clipToBounds

default final @NonNull Modifier ClipKt.clipToBounds(@NonNull Modifier receiver)

Clip the content to the bounds of a layer defined at this modifier.

ClipScrollableContainerKt.clipScrollableContainer

default final @NonNull Modifier ClipScrollableContainerKt.clipScrollableContainer(
    @NonNull Modifier receiver,
    @NonNull Orientation orientation
)

Clips bounds of scrollable container on main axis while leaving space for background effects (like shadows) on cross axis.

Parameters
@NonNull Orientation orientation

orientation of the scrolling

ComposedModifierKt.composed

default final @NonNull Modifier ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies. composed may be used to implement stateful modifiers that have instance-specific state for each modified element, allowing the same Modifier instance to be safely reused for multiple elements while maintaining element-specific state.

If inspectorInfo is specified this modifier will be visible to tools during development. Specify the name and arguments of the original modifier.

Example usage:

import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo

// let's create your own custom stateful modifier
fun Modifier.myColorModifier(color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myColorModifier"
        // specify a single argument as the value when the argument name is irrelevant
        value = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp

// let's create your own custom stateful modifier with multiple arguments
fun Modifier.myModifier(width: Dp, height: Dp, color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myModifier"
        // add name and value of each argument
        properties["width"] = width
        properties["height"] = height
        properties["color"] = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)

materialize must be called to create instance-specific modifiers if you are directly applying a Modifier to an element tree node.

ComposedModifierKt.composed

@ExperimentalComposeUiApi
default final @NonNull Modifier ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies. composed may be used to implement stateful modifiers that have instance-specific state for each modified element, allowing the same Modifier instance to be safely reused for multiple elements while maintaining element-specific state.

When keys are provided, composed produces a Modifier that will compare equals to another modifier constructed with the same keys in order to take advantage of caching and skipping optimizations. fullyQualifiedName should be the fully-qualified import name for your modifier factory function, e.g. com.example.myapp.ui.fancyPadding.

If inspectorInfo is specified this modifier will be visible to tools during development. Specify the name and arguments of the original modifier.

Example usage:

import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo

// let's create your own custom stateful modifier
fun Modifier.myColorModifier(color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myColorModifier"
        // specify a single argument as the value when the argument name is irrelevant
        value = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp

// let's create your own custom stateful modifier with multiple arguments
fun Modifier.myModifier(width: Dp, height: Dp, color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myModifier"
        // add name and value of each argument
        properties["width"] = width
        properties["height"] = height
        properties["color"] = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)

materialize must be called to create instance-specific modifiers if you are directly applying a Modifier to an element tree node.

ComposedModifierKt.composed

@ExperimentalComposeUiApi
default final @NonNull Modifier ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object keys,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies. composed may be used to implement stateful modifiers that have instance-specific state for each modified element, allowing the same Modifier instance to be safely reused for multiple elements while maintaining element-specific state.

When keys are provided, composed produces a Modifier that will compare equals to another modifier constructed with the same keys in order to take advantage of caching and skipping optimizations. fullyQualifiedName should be the fully-qualified import name for your modifier factory function, e.g. com.example.myapp.ui.fancyPadding.

If inspectorInfo is specified this modifier will be visible to tools during development. Specify the name and arguments of the original modifier.

Example usage:

import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo

// let's create your own custom stateful modifier
fun Modifier.myColorModifier(color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myColorModifier"
        // specify a single argument as the value when the argument name is irrelevant
        value = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp

// let's create your own custom stateful modifier with multiple arguments
fun Modifier.myModifier(width: Dp, height: Dp, color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myModifier"
        // add name and value of each argument
        properties["width"] = width
        properties["height"] = height
        properties["color"] = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)

materialize must be called to create instance-specific modifiers if you are directly applying a Modifier to an element tree node.

ComposedModifierKt.composed

@ExperimentalComposeUiApi
default final @NonNull Modifier ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    Object key2,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies. composed may be used to implement stateful modifiers that have instance-specific state for each modified element, allowing the same Modifier instance to be safely reused for multiple elements while maintaining element-specific state.

When keys are provided, composed produces a Modifier that will compare equals to another modifier constructed with the same keys in order to take advantage of caching and skipping optimizations. fullyQualifiedName should be the fully-qualified import name for your modifier factory function, e.g. com.example.myapp.ui.fancyPadding.

If inspectorInfo is specified this modifier will be visible to tools during development. Specify the name and arguments of the original modifier.

Example usage:

import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo

// let's create your own custom stateful modifier
fun Modifier.myColorModifier(color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myColorModifier"
        // specify a single argument as the value when the argument name is irrelevant
        value = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp

// let's create your own custom stateful modifier with multiple arguments
fun Modifier.myModifier(width: Dp, height: Dp, color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myModifier"
        // add name and value of each argument
        properties["width"] = width
        properties["height"] = height
        properties["color"] = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)

materialize must be called to create instance-specific modifiers if you are directly applying a Modifier to an element tree node.

ComposedModifierKt.composed

@ExperimentalComposeUiApi
default final @NonNull Modifier ComposedModifierKt.composed(
    @NonNull Modifier receiver,
    @NonNull String fullyQualifiedName,
    Object key1,
    Object key2,
    Object key3,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @Composable @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Declare a just-in-time composition of a Modifier that will be composed for each element it modifies. composed may be used to implement stateful modifiers that have instance-specific state for each modified element, allowing the same Modifier instance to be safely reused for multiple elements while maintaining element-specific state.

When keys are provided, composed produces a Modifier that will compare equals to another modifier constructed with the same keys in order to take advantage of caching and skipping optimizations. fullyQualifiedName should be the fully-qualified import name for your modifier factory function, e.g. com.example.myapp.ui.fancyPadding.

If inspectorInfo is specified this modifier will be visible to tools during development. Specify the name and arguments of the original modifier.

Example usage:

import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo

// let's create your own custom stateful modifier
fun Modifier.myColorModifier(color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myColorModifier"
        // specify a single argument as the value when the argument name is irrelevant
        value = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.unit.Dp

// let's create your own custom stateful modifier with multiple arguments
fun Modifier.myModifier(width: Dp, height: Dp, color: Color) = composed(
    // pass inspector information for debug
    inspectorInfo = debugInspectorInfo {
        // name should match the name of the modifier
        name = "myModifier"
        // add name and value of each argument
        properties["width"] = width
        properties["height"] = height
        properties["color"] = color
    },
    // pass your modifier implementation that resolved per modified element
    factory = {
        // add your modifier implementation here
        Modifier
    }
)

materialize must be called to create instance-specific modifiers if you are directly applying a Modifier to an element tree node.

DrawModifierKt.drawBehind

default final @NonNull Modifier DrawModifierKt.drawBehind(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> onDraw
)

Draw into a Canvas behind the modified content.

DrawModifierKt.drawWithCache

default final @NonNull Modifier DrawModifierKt.drawWithCache(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull CacheDrawScope, @NonNull DrawResult> onBuildDrawCache
)

Draw into a DrawScope with content that is persisted across draw calls as long as the size of the drawing area is the same or any state objects that are read have not changed. In the event that the drawing area changes, or the underlying state values that are being read change, this method is invoked again to recreate objects to be used during drawing

For example, a androidx.compose.ui.graphics.LinearGradient that is to occupy the full bounds of the drawing area can be created once the size has been defined and referenced for subsequent draw calls without having to re-allocate.

import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color

Box(
    Modifier.drawWithCache {
        val gradient = Brush.linearGradient(
            colors = listOf(Color.Red, Color.Blue),
            start = Offset.Zero,
            end = Offset(size.width, size.height)
        )
        onDrawBehind {
            drawRect(gradient)
        }
    }
)
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color

val colors1 = listOf(Color.Red, Color.Blue)
val colors2 = listOf(Color.Yellow, Color.Green)
var toggle by remember { mutableStateOf(true) }
Box(
    Modifier.clickable { toggle = !toggle }.drawWithCache {
        val gradient = Brush.linearGradient(
            colors = if (toggle) colors1 else colors2,
            start = Offset.Zero,
            end = Offset(size.width, size.height)
        )
        onDrawBehind {
            drawRect(gradient)
        }
    }
)
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.Path
import androidx.compose.ui.graphics.vector.PathData
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.dp

val vectorPainter = rememberVectorPainter(24.dp, 24.dp, autoMirror = true) {
        viewportWidth, viewportHeight ->
    Path(
        pathData = PathData {
            lineTo(viewportWidth, 0f)
            lineTo(0f, viewportHeight)
            close()
        },
        fill = SolidColor(Color.Black)
    )
}
Image(
    painter = vectorPainter,
    contentDescription = null,
    modifier = Modifier.requiredSize(120.dp).drawWithCache {
        val gradient = Brush.linearGradient(
            colors = listOf(Color.Red, Color.Blue),
            start = Offset.Zero,
            end = Offset(0f, size.height)
        )
        onDrawWithContent {
            drawContent()
            drawRect(gradient, blendMode = BlendMode.Plus)
        }
    }
)

DrawModifierKt.drawWithContent

default final @NonNull Modifier DrawModifierKt.drawWithContent(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull ContentDrawScopeUnit> onDraw
)

Creates a DrawModifier that allows the developer to draw before or after the layout's contents. It also allows the modifier to adjust the layout's canvas.

ExcludeFromSystemGestureKt.excludeFromSystemGesture

default final @NonNull Modifier ExcludeFromSystemGestureKt.excludeFromSystemGesture(
    @NonNull Modifier receiver
)

Excludes the layout rectangle from the system gesture.

ExcludeFromSystemGestureKt.excludeFromSystemGesture

default final @NonNull Modifier ExcludeFromSystemGestureKt.excludeFromSystemGesture(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinates, @NonNull Rect> exclusion
)

Excludes a rectangle within the local layout coordinates from the system gesture. After layout, exclusion is called to determine the Rect to exclude from the system gesture area.

The LayoutCoordinates of the Modifier's location in the layout is passed as passed as exclusion's parameter.

FocusChangedModifierKt.onFocusChanged

default final @NonNull Modifier FocusChangedModifierKt.onFocusChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusChanged
)

Add this modifier to a component to observe focus state events. onFocusChanged is invoked when the focus state changes. The onFocusChanged modifier listens to the state of the first focusTarget following this modifier.

import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.unit.dp

var color by remember { mutableStateOf(Black) }
Box(
    Modifier
        .border(2.dp, color)
        // The onFocusChanged should be added BEFORE the focusable that is being observed.
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusable()
)

Note: If you want to be notified every time the internal focus state is written to (even if it hasn't changed), use onFocusEvent instead.

FocusEventModifierKt.onFocusEvent

default final @NonNull Modifier FocusEventModifierKt.onFocusEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusEvent
)

Add this modifier to a component to observe focus state events.

FocusModifierKt.focusModifier

default final @NonNull Modifier FocusModifierKt.focusModifier(@NonNull Modifier receiver)

Add this modifier to a component to make it focusable.

FocusModifierKt.focusTarget

default final @NonNull Modifier FocusModifierKt.focusTarget(@NonNull Modifier receiver)

Add this modifier to a component to make it focusable.

Focus state is stored within this modifier. The bounds of this modifier reflect the bounds of the focus box.

Note: This is a low level modifier. Before using this consider using Modifier.focusable(). It uses a focusTarget in its implementation. Modifier.focusable() adds semantics that are needed for accessibility.

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.unit.dp

var color by remember { mutableStateOf(Black) }
Box(
    Modifier
        .border(2.dp, color)
        // The onFocusChanged should be added BEFORE the focusTarget that is being observed.
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusTarget()
)

FocusOrderModifierKt.focusOrder

default final @NonNull Modifier FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull FocusOrderUnit> focusOrderReceiver
)

Use this modifier to specify a custom focus traversal order.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester

Column(Modifier.fillMaxSize(), Arrangement.SpaceEvenly) {
    val (item1, item2, item3, item4) = remember { FocusRequester.createRefs() }
    Row(Modifier.fillMaxWidth(), Arrangement.SpaceEvenly) {
        Box(
            Modifier
                .focusRequester(item1)
                .focusProperties {
                    next = item2
                    right = item2
                    down = item3
                    previous = item4
                }
                .focusable()
        )
        Box(
            Modifier
                .focusRequester(item2)
                .focusProperties {
                    next = item3
                    right = item1
                    down = item4
                    previous = item1
                }
                .focusable()
        )
    }
    Row(Modifier.fillMaxWidth(), Arrangement.SpaceEvenly) {
        Box(
            Modifier
                .focusRequester(item3)
                .focusProperties {
                    next = item4
                    right = item4
                    up = item1
                    previous = item2
                }
        )
        Box(
            Modifier
                .focusRequester(item4)
                .focusProperties {
                    next = item1
                    left = item3
                    up = item2
                    previous = item3
                }
        )
    }
}
Parameters
@ExtensionFunctionType @NonNull Function1<@NonNull FocusOrderUnit> focusOrderReceiver

Specifies FocusRequesters that are used when the user wants to move the current focus to the next item, or wants to move focus left, right, up or down.

FocusOrderModifierKt.focusOrder

default final @NonNull Modifier FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester
)

A modifier that lets you specify a FocusRequester for the current composable so that this focusRequester can be used by another composable to specify a custom focus order.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester

Column(Modifier.fillMaxSize(), Arrangement.SpaceEvenly) {
    val (item1, item2, item3, item4) = remember { FocusRequester.createRefs() }
    Row(Modifier.fillMaxWidth(), Arrangement.SpaceEvenly) {
        Box(
            Modifier
                .focusRequester(item1)
                .focusProperties {
                    next = item2
                    right = item2
                    down = item3
                    previous = item4
                }
                .focusable()
        )
        Box(
            Modifier
                .focusRequester(item2)
                .focusProperties {
                    next = item3
                    right = item1
                    down = item4
                    previous = item1
                }
                .focusable()
        )
    }
    Row(Modifier.fillMaxWidth(), Arrangement.SpaceEvenly) {
        Box(
            Modifier
                .focusRequester(item3)
                .focusProperties {
                    next = item4
                    right = item4
                    up = item1
                    previous = item2
                }
        )
        Box(
            Modifier
                .focusRequester(item4)
                .focusProperties {
                    next = item1
                    left = item3
                    up = item2
                    previous = item3
                }
        )
    }
}

FocusOrderModifierKt.focusOrder

default final @NonNull Modifier FocusOrderModifierKt.focusOrder(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester,
    @ExtensionFunctionType @NonNull Function1<@NonNull FocusOrderUnit> focusOrderReceiver
)

A modifier that lets you specify a FocusRequester for the current composable along with focusOrder.

FocusPropertiesKt.focusProperties

default final @NonNull Modifier FocusPropertiesKt.focusProperties(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull FocusPropertiesUnit> scope
)

This modifier allows you to specify properties that are accessible to focusTargets further down the modifier chain or on child layout nodes.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.input.InputMode.Companion.Touch
import androidx.compose.ui.platform.LocalInputModeManager

Column {
    // Always focusable.
    Box(modifier = Modifier
        .focusProperties { canFocus = true }
        .focusTarget()
    )
    // Only focusable in non-touch mode.
    val inputModeManager = LocalInputModeManager.current
    Box(modifier = Modifier
        .focusProperties { canFocus = inputModeManager.inputMode != Touch }
        .focusTarget()
    )
}

FocusRequesterModifierKt.focusRequester

default final @NonNull Modifier FocusRequesterModifierKt.focusRequester(
    @NonNull Modifier receiver,
    @NonNull FocusRequester focusRequester
)

Add this modifier to a component to request changes to focus.

import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.unit.dp

val focusRequester = remember { FocusRequester() }
var color by remember { mutableStateOf(Black) }
Box(
    Modifier
        .clickable { focusRequester.requestFocus() }
        .border(2.dp, color)
        // The focusRequester should be added BEFORE the focusable.
        .focusRequester(focusRequester)
        // The onFocusChanged should be added BEFORE the focusable that is being observed.
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusable()
)

FocusableKt.focusGroup

@ExperimentalFoundationApi
default final @NonNull Modifier FocusableKt.focusGroup(@NonNull Modifier receiver)

Creates a focus group or marks this component as a focus group. This means that when we move focus using the keyboard or programmatically using FocusManager.moveFocus(), the items within the focus group will be given a higher priority before focus moves to items outside the focus group.

In the sample below, each column is a focus group, so pressing the tab key will move focus to all the buttons in column 1 before visiting column 2.

import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.ui.Modifier

Row {
    Column(Modifier.focusGroup()) {
        Button({}) { Text("Row1 Col1") }
        Button({}) { Text("Row2 Col1") }
        Button({}) { Text("Row3 Col1") }
    }
    Column(Modifier.focusGroup()) {
        Button({}) { Text("Row1 Col2") }
        Button({}) { Text("Row2 Col2") }
        Button({}) { Text("Row3 Col2") }
    }
}

Note: The focusable children of a focusable parent automatically form a focus group. This modifier is to be used when you want to create a focus group where the parent is not focusable. If you encounter a component that uses a focusGroup internally, you can make it focusable by using a focusable modifier. In the second sample here, the LazyRow is a focus group that is not itself focusable. But you can make it focusable by adding a focusable modifier.

import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Red
import androidx.compose.ui.unit.dp

val interactionSource = remember { MutableInteractionSource() }
LazyRow(
    Modifier
        .focusable(interactionSource = interactionSource)
        .border(1.dp, if (interactionSource.collectIsFocusedAsState().value) Red else Black)
) {
    repeat(10) {
        item {
            Button({}) { Text("Button$it") }
        }
    }
}

FocusableKt.focusable

default final @NonNull Modifier FocusableKt.focusable(
    @NonNull Modifier receiver,
    boolean enabled,
    MutableInteractionSource interactionSource
)

Configure component to be focusable via focus system or accessibility "focus" event.

Add this modifier to the element to make it focusable within its bounds.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester

// initialize focus reference to be able to request focus programmatically
val focusRequester = remember { FocusRequester() }
// MutableInteractionSource to track changes of the component's interactions (like "focused")
val interactionSource = remember { MutableInteractionSource() }

// text below will change when we focus it via button click
val isFocused = interactionSource.collectIsFocusedAsState().value
val text = if (isFocused) {
    "Focused! tap anywhere to free the focus"
} else {
    "Bring focus to me by tapping the button below!"
}
Column {
    // this Text will change it's text parameter depending on the presence of a focus
    Text(
        text = text,
        modifier = Modifier
            // add focusRequester modifier before the focusable (or even in the parent)
            .focusRequester(focusRequester)
            .focusable(interactionSource = interactionSource)
    )
    Button(onClick = { focusRequester.requestFocus() }) {
        Text("Bring focus to the text above")
    }
}
Parameters
boolean enabled

Controls the enabled state. When false, element won't participate in the focus

MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit FocusInteraction.Focus when this element is being focused.

FocusedBoundsKt.onFocusedBoundsChanged

@ExperimentalFoundationApi
default final @NonNull Modifier FocusedBoundsKt.onFocusedBoundsChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<LayoutCoordinatesUnit> onPositioned
)

Calls onPositioned whenever the bounds of the currently-focused area changes. If a child of this node has focus, onPositioned will be called immediately with a non-null LayoutCoordinates that can be queried for the focused bounds, and again every time the focused child changes or is repositioned. When a child loses focus, onPositioned will be passed null.

When an event occurs, it is bubbled up from the focusable node, so the nearest parent gets the event first, and then its parent, etc.

Note that there may be some cases where the focused bounds change but the callback is not invoked, but the last LayoutCoordinates will always return the most up-to-date bounds.

GraphicsLayerModifierKt.graphicsLayer

default final @NonNull Modifier GraphicsLayerModifierKt.graphicsLayer(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull GraphicsLayerScopeUnit> block
)

A Modifier.Node that makes content draw into a draw layer. The draw layer can be invalidated separately from parents. A graphicsLayer should be used when the content updates independently from anything above it to minimize the invalidated content.

graphicsLayer can be used to apply effects to content, such as scaling, rotation, opacity, shadow, and clipping. Prefer this version when you have layer properties backed by a androidx.compose.runtime.State or an animated value as reading a state inside block will only cause the layer properties update without triggering recomposition and relayout.

import androidx.compose.animation.core.Animatable
import androidx.compose.material.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer

val animatedAlpha = remember { Animatable(0f) }
Text(
    "Hello World",
    Modifier.graphicsLayer {
        alpha = animatedAlpha.value
        clip = true
    }
)
LaunchedEffect(animatedAlpha) {
    animatedAlpha.animateTo(1f)
}
Parameters
@ExtensionFunctionType @NonNull Function1<@NonNull GraphicsLayerScopeUnit> block

block on GraphicsLayerScope where you define the layer properties.

GraphicsLayerModifierKt.graphicsLayer

default final @NonNull Modifier GraphicsLayerModifierKt.graphicsLayer(
    @NonNull Modifier receiver,
    float scaleX,
    float scaleY,
    float alpha,
    float translationX,
    float translationY,
    float shadowElevation,
    float rotationX,
    float rotationY,
    float rotationZ,
    float cameraDistance,
    @NonNull TransformOrigin transformOrigin,
    @NonNull Shape shape,
    boolean clip,
    RenderEffect renderEffect,
    @NonNull Color ambientShadowColor,
    @NonNull Color spotShadowColor,
    @NonNull CompositingStrategy compositingStrategy
)

A Modifier.Element that makes content draw into a draw layer. The draw layer can be invalidated separately from parents. A graphicsLayer should be used when the content updates independently from anything above it to minimize the invalidated content.

graphicsLayer can also be used to apply effects to content, such as scaling (scaleX, scaleY), rotation (rotationX, rotationY, rotationZ), opacity (alpha), shadow (shadowElevation, shape), clipping (clip, shape), as well as altering the result of the layer with RenderEffect. Shadow color and ambient colors can be modified by configuring the spotShadowColor and ambientShadowColor respectively.

CompositingStrategy determines whether or not the contents of this layer are rendered into an offscreen buffer. This is useful in order to optimize alpha usages with CompositingStrategy.ModulateAlpha which will skip the overhead of an offscreen buffer but can generate different rendering results depending on whether or not the contents of the layer are overlapping. Similarly leveraging CompositingStrategy.Offscreen is useful in situations where creating an offscreen buffer is preferred usually in conjunction with BlendMode usage.

Note that if you provide a non-zero shadowElevation and if the passed shape is concave the shadow will not be drawn on Android versions less than 10.

Also note that alpha values less than 1.0f will have their contents implicitly clipped to their bounds unless CompositingStrategy.ModulateAlpha is specified. This is because an intermediate compositing layer is created to render contents into first before being drawn into the destination with the desired alpha. This layer is sized to the bounds of the composable this modifier is configured on, and contents outside of these bounds are omitted.

If the layer parameters are backed by a androidx.compose.runtime.State or an animated value prefer an overload with a lambda block on GraphicsLayerScope as reading a state inside the block will only cause the layer properties update without triggering recomposition and relayout.

import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer

Text("Hello World", Modifier.graphicsLayer(alpha = 0.5f, clip = true))
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp

Canvas(
    modifier =
        Modifier.size(100.dp)
        .background(Color.Black)
        .graphicsLayer(
            alpha = 0.5f,
            compositingStrategy = CompositingStrategy.ModulateAlpha
        )
) {
    // Configuring an alpha less than 1.0 and specifying
    // CompositingStrategy.ModulateAlpha ends up with the overlapping region
    // of the 2 draw rect calls to blend transparent blue and transparent red
    // against the black background instead of just transparent blue which is what would
    // occur with CompositingStrategy.Auto or CompositingStrategy.Offscreen
    inset(0f, 0f, size.width / 3, size.height / 3) {
        drawRect(color = Color.Red)
    }
    inset(size.width / 3, size.height / 3, 0f, 0f) {
        drawRect(color = Color.Blue)
    }
}

GraphicsLayerModifierKt.toolingGraphicsLayer

default final @NonNull Modifier GraphicsLayerModifierKt.toolingGraphicsLayer(
    @NonNull Modifier receiver
)

A Modifier.Element that adds a draw layer such that tooling can identify an element in the drawn image.

HoverableKt.hoverable

default final @NonNull Modifier HoverableKt.hoverable(
    @NonNull Modifier receiver,
    @NonNull MutableInteractionSource interactionSource,
    boolean enabled
)

Configure component to be hoverable via pointer enter/exit events.

import androidx.compose.foundation.background
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// MutableInteractionSource to track changes of the component's interactions (like "hovered")
val interactionSource = remember { MutableInteractionSource() }
val isHovered by interactionSource.collectIsHoveredAsState()

// the color will change depending on the presence of a hover
Box(
    modifier = Modifier
        .size(128.dp)
        .background(if (isHovered) Color.Red else Color.Blue)
        .hoverable(interactionSource = interactionSource),
    contentAlignment = Alignment.Center
) {
    Text(if (isHovered) "Hovered" else "Unhovered")
}
Parameters
@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit HoverInteraction.Enter when this element is being hovered.

boolean enabled

Controls the enabled state. When false, hover events will be ignored.

IndicationKt.indication

default final @NonNull Modifier IndicationKt.indication(
    @NonNull Modifier receiver,
    @NonNull InteractionSource interactionSource,
    Indication indication
)

Draws visual effects for this component when interactions occur.

import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.material.Text
import androidx.compose.material.ripple.rememberRipple
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

val interactionSource = remember { MutableInteractionSource() }
Column {
    Text(
        text = "Click me and my neighbour will indicate as well!",
        modifier = Modifier
            // clickable will dispatch events using MutableInteractionSource and show ripple
            .clickable(
                interactionSource = interactionSource,
                indication = rememberRipple()
            ) {
                /**do something */
            }
            .padding(10.dp)
    )
    Spacer(Modifier.requiredHeight(10.dp))
    Text(
        text = "I'm neighbour and I indicate when you click the other one",
        modifier = Modifier
            // this element doesn't have a click, but will show default indication from the
            // CompositionLocal as it accepts the same MutableInteractionSource
            .indication(interactionSource, LocalIndication.current)
            .padding(10.dp)
    )
}
Parameters
@NonNull InteractionSource interactionSource

InteractionSource that will be used by indication to draw visual effects - this InteractionSource represents the stream of Interactions for this component.

Indication indication

Indication used to draw visual effects. If null, no visual effects will be shown for this component.

InspectableValueKt.inspectable

default final @NonNull Modifier InspectableValueKt.inspectable(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull InspectorInfoUnit> inspectorInfo,
    @ExtensionFunctionType @NonNull Function1<@NonNull Modifier, @NonNull Modifier> factory
)

Use this to group a common set of modifiers and provide InspectorInfo for the resulting modifier.

import androidx.compose.foundation.background
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.platform.inspectable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

/**
 * Sample with a single parameter
 */
fun Modifier.simpleFrame(color: Color) = inspectable(
    inspectorInfo = debugInspectorInfo {
        name = "simpleFrame"
        value = color
    }
) {
    background(color, RoundedCornerShape(5.0.dp))
}

/**
 * Sample with multiple parameters
 */
fun Modifier.fancyFrame(size: Dp, color: Color) = inspectable(
    inspectorInfo = debugInspectorInfo {
        name = "fancyFrame"
        properties["size"] = size
        properties["color"] = color
    }
) {
    background(color, RoundedCornerShape(size))
}

InteractiveComponentSizeKt.minimumInteractiveComponentSize

default final @NonNull Modifier InteractiveComponentSizeKt.minimumInteractiveComponentSize(
    @NonNull Modifier receiver
)

Reserves at least 48.dp in size to disambiguate touch interactions if the element would measure smaller.

https://m3.material.io/foundations/accessible-design/accessibility-basics#28032e45-c598-450c-b355-f9fe737b1cd8

This uses the Material recommended minimum size of 48.dp x 48.dp, which may not the same as the system enforced minimum size. The minimum clickable / touch target size (48.dp by default) is controlled by the system via ViewConfiguration` and automatically expanded at the touch input layer.

This modifier is not needed for touch target expansion to happen. It only affects layout, to make sure there is adequate space for touch target expansion.

IntrinsicKt.height

default final @NonNull Modifier IntrinsicKt.height(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the preferred height of the content to be the same as the min or max intrinsic height of the content. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

See width for other options of sizing to intrinsic width. Also see height and heightIn for other options to set the preferred height.

Example usage for min intrinsic:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Builds a layout containing two pieces of text separated by a divider, where the divider
// is sized according to the height of the longest text.
//
// Here height min intrinsic is adding a height premeasurement pass for the Row,
// whose minimum intrinsic height will correspond to the height of the largest Text. Then
// height min intrinsic will measure the Row with tight height, the same as the
// premeasured minimum intrinsic height, which due to fillMaxHeight will force the Texts and
// the divider to use the same height.
Box {
    Row(Modifier.height(IntrinsicSize.Min)) {
        Text(
            text = "This is a really short text",
            modifier = Modifier.weight(1f).fillMaxHeight()
        )
        Box(Modifier.width(1.dp).fillMaxHeight().background(Color.Black))
        Text(
            text = "This is a much much much much much much much much much much" +
                " much much much much much much longer text",
            modifier = Modifier.weight(1f).fillMaxHeight()
        )
    }
}

Example usage for max intrinsic:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Builds a layout containing two aspectRatios separated by a divider, where the divider
// is sized according to the height of the taller aspectRatio.
//
// Here height max intrinsic is adding a height premeasurement pass for the
// Row, whose maximum intrinsic height will correspond to the height of the taller
// aspectRatio. Then height max intrinsic will measure the Row with tight height,
// the same as the premeasured maximum intrinsic height, which due to fillMaxHeight modifier
// will force the aspectRatios and the divider to use the same height.
//
Box {
    Row(Modifier.height(IntrinsicSize.Max)) {
        val modifier = Modifier.fillMaxHeight().weight(1f)
        Box(modifier.aspectRatio(2f).background(Color.Gray))
        Box(Modifier.width(1.dp).fillMaxHeight().background(Color.Black))
        Box(modifier.aspectRatio(1f).background(Color.Blue))
    }
}

IntrinsicKt.requiredHeight

default final @NonNull Modifier IntrinsicKt.requiredHeight(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the height of the content to be exactly the same as the min or max intrinsic height of the content. The incoming measurement Constraints will not override this value. If the content intrinsic height does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See width for options of sizing to intrinsic width. See height and heightIn for options to set the preferred height. See requiredHeight and requiredHeightIn for other options to set the required height.

IntrinsicKt.requiredWidth

default final @NonNull Modifier IntrinsicKt.requiredWidth(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the width of the content to be exactly the same as the min or max intrinsic width of the content. The incoming measurement Constraints will not override this value. If the content intrinsic width does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See height for options of sizing to intrinsic height. See width and widthIn for options to set the preferred width. See requiredWidth and requiredWidthIn for other options to set the required width.

IntrinsicKt.width

default final @NonNull Modifier IntrinsicKt.width(
    @NonNull Modifier receiver,
    @NonNull IntrinsicSize intrinsicSize
)

Declare the preferred width of the content to be the same as the min or max intrinsic width of the content. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

See height for options of sizing to intrinsic height. Also see width and widthIn for other options to set the preferred width.

Example usage for min intrinsic:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Builds a layout containing three Box having the same width as the widest one.
//
// Here width min intrinsic is adding a width premeasurement pass for the
// Column, whose minimum intrinsic width will correspond to the preferred width of the largest
// Box. Then width min intrinsic will measure the Column with tight width, the
// same as the premeasured minimum intrinsic width, which due to fillMaxWidth will force
// the Box's to use the same width.
Box {
    Column(Modifier.width(IntrinsicSize.Min).fillMaxHeight()) {
        Box(
            modifier = Modifier.fillMaxWidth()
                .size(20.dp, 10.dp)
                .background(Color.Gray)
        )
        Box(
            modifier = Modifier.fillMaxWidth()
                .size(30.dp, 10.dp)
                .background(Color.Blue)
        )
        Box(
            modifier = Modifier.fillMaxWidth()
                .size(10.dp, 10.dp)
                .background(Color.Magenta)
        )
    }
}

Example usage for max intrinsic:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

// Builds a layout containing three Text boxes having the same width as the widest one.
//
// Here width max intrinsic is adding a width premeasurement pass for the Column,
// whose maximum intrinsic width will correspond to the preferred width of the largest
// Box. Then width max intrinsic will measure the Column with tight width, the
// same as the premeasured maximum intrinsic width, which due to fillMaxWidth modifiers will
// force the Boxs to use the same width.

Box {
    Column(Modifier.width(IntrinsicSize.Max).fillMaxHeight()) {
        Box(Modifier.fillMaxWidth().background(Color.Gray)) {
            Text("Short text")
        }
        Box(Modifier.fillMaxWidth().background(Color.Blue)) {
            Text("Extremely long text giving the width of its siblings")
        }
        Box(Modifier.fillMaxWidth().background(Color.Magenta)) {
            Text("Medium length text")
        }
    }
}

KeyInputModifierKt.onKeyEvent

default final @NonNull Modifier KeyInputModifierKt.onKeyEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onKeyEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events when it (or one of its children) is focused.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent

// When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
// and then back up to the parent. At any stage you can stop the propagation by returning
// true to indicate that you consumed the event.
Box(
    Modifier
        .onPreviewKeyEvent { keyEvent1 -> false }
        .onKeyEvent { keyEvent4 -> false }
) {
    Box(
        Modifier
            .onPreviewKeyEvent { keyEvent2 -> false }
            .onKeyEvent { keyEvent3 -> false }
            .focusable()
    )
}
Parameters
@NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onKeyEvent

This callback is invoked when the user interacts with the hardware keyboard. While implementing this callback, return true to stop propagation of this event. If you return false, the key event will be sent to this onKeyEvent's parent.

KeyInputModifierKt.onPreviewKeyEvent

default final @NonNull Modifier KeyInputModifierKt.onPreviewKeyEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onPreviewKeyEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events when it (or one of its children) is focused.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent

// When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
// and then back up to the parent. At any stage you can stop the propagation by returning
// true to indicate that you consumed the event.
Box(
    Modifier
        .onPreviewKeyEvent { keyEvent1 -> false }
        .onKeyEvent { keyEvent4 -> false }
) {
    Box(
        Modifier
            .onPreviewKeyEvent { keyEvent2 -> false }
            .onKeyEvent { keyEvent3 -> false }
            .focusable()
    )
}
Parameters
@NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onPreviewKeyEvent

This callback is invoked when the user interacts with the hardware keyboard. It gives ancestors of a focused component the chance to intercept a KeyEvent. Return true to stop propagation of this event. If you return false, the key event will be sent to this onPreviewKeyEvent's child. If none of the children consume the event, it will be sent back up to the root KeyInputModifierNode using the onKeyEvent callback.

LayoutIdKt.layoutId

default final @NonNull Modifier LayoutIdKt.layoutId(@NonNull Modifier receiver, @NonNull Object layoutId)

Tag the element with layoutId to identify the element within its parent.

Example usage:

import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.unit.Constraints

Layout({
    // Here the Containers are only needed to apply the modifiers. You could use the
    // modifier on header and footer directly if they are composables accepting modifiers.
    Box(Modifier.layoutId("header")) { header() }
    Box(Modifier.layoutId("footer")) { footer() }
}) { measurables, constraints ->
    val placeables = measurables.map { measurable ->
        when (measurable.layoutId) {
            // You should use appropriate constraints. Here we measure fake constraints.
            "header" -> measurable.measure(Constraints.fixed(100, 100))
            "footer" -> measurable.measure(constraints)
            else -> error("Unexpected tag")
        }
    }
    // Size should be derived from children measured sizes on placeables,
    // but this is simplified for the purposes of the example.
    layout(100, 100) {
        placeables.forEach { it.placeRelative(0, 0) }
    }
}

LayoutModifierKt.layout

default final @NonNull Modifier LayoutModifierKt.layout(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function3<@NonNull MeasureScope, @NonNull Measurable, @NonNull Constraints, @NonNull MeasureResult> measure
)

Creates a LayoutModifier that allows changing how the wrapped element is measured and laid out.

This is a convenience API of creating a custom LayoutModifier modifier, without having to create a class or an object that implements the LayoutModifier interface. The intrinsic measurements follow the default logic provided by the LayoutModifier.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.offset

Box(
    Modifier.background(Color.Gray)
        .layout { measurable, constraints ->
            // an example modifier that adds 50 pixels of vertical padding.
            val padding = 50
            val placeable = measurable.measure(constraints.offset(vertical = -padding))
            layout(placeable.width, placeable.height + padding) {
                placeable.placeRelative(0, padding)
            }
        }
) {
    Box(Modifier.fillMaxSize().background(Color.DarkGray))
}
See also
LayoutModifier

LookaheadScopeKt.intermediateLayout

@ExperimentalComposeUiApi
default final @NonNull Modifier LookaheadScopeKt.intermediateLayout(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function3<@NonNull IntermediateMeasureScope, @NonNull Measurable, @NonNull Constraints, @NonNull MeasureResult> measure
)

Creates an intermediate layout intended to help morph the layout from the current layout to the lookahead (i.e. pre-calculated future) layout.

This modifier will be invoked after lookahead pass and will have access to the lookahead results in measure. Therefore:

  1. intermediateLayout measure/layout logic will not affect lookahead pass, but only be invoked during the main measure/layout pass, and 2) measure block can define intermediate changes that morphs the layout in the main pass gradually until it converges lookahead pass.

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationVector2D
import androidx.compose.animation.core.VectorConverter
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.intermediateLayout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round

// Creates a custom modifier that animates the constraints and measures child with the
// animated constraints. This modifier is built on top of `Modifier.intermediateLayout`, which
// allows access to the lookahead size of the layout. A resize animation will be kicked off
// whenever the lookahead size changes, to animate children from current size to lookahead size.
// Fixed constraints created based on the animation value will be used to measure
// child, so the child layout gradually changes its size and potentially its child's placement
// to fit within the animated constraints.
fun Modifier.animateConstraints() = composed {
    // Creates a size animation
    var sizeAnimation: Animatable<IntSize, AnimationVector2D>? by remember {
        mutableStateOf(null)
    }

    this.intermediateLayout { measurable, _ ->
        // When layout changes, the lookahead pass will calculate a new final size for the
        // child layout. This lookahead size can be used to animate the size
        // change, such that the animation starts from the current size and gradually
        // change towards `lookaheadSize`.
        if (lookaheadSize != sizeAnimation?.targetValue) {
            sizeAnimation?.run {
                launch { animateTo(lookaheadSize) }
            } ?: Animatable(lookaheadSize, IntSize.VectorConverter).let {
                sizeAnimation = it
            }
        }
        val (width, height) = sizeAnimation!!.value
        // Creates a fixed set of constraints using the animated size
        val animatedConstraints = Constraints.fixed(width, height)
        // Measure child with animated constraints.
        val placeable = measurable.measure(animatedConstraints)
        layout(placeable.width, placeable.height) {
            placeable.place(0, 0)
        }
    }
}

var fullWidth by remember { mutableStateOf(false) }
Row(
    (if (fullWidth) Modifier.fillMaxWidth() else Modifier.width(100.dp))
        .height(200.dp)
        // Use the custom modifier created above to animate the constraints passed
        // to the child, and therefore resize children in an animation.
        .animateConstraints()
        .clickable { fullWidth = !fullWidth }) {
    Box(
        Modifier
            .weight(1f)
            .fillMaxHeight()
            .background(Color.Red)
    )
    Box(
        Modifier
            .weight(2f)
            .fillMaxHeight()
            .background(Color.Yellow)
    )
}

MagnifierKt.magnifier

@ExperimentalFoundationApi
default final @NonNull Modifier MagnifierKt.magnifier(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> sourceCenter,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> magnifierCenter,
    float zoom,
    @NonNull MagnifierStyle style,
    Function1<@NonNull DpSizeUnit> onSizeChanged
)

Shows a Magnifier widget that shows an enlarged version of the content at sourceCenter relative to the current layout node.

This function returns a no-op modifier on API levels below P (28), since the framework does not support the Magnifier widget on those levels. However, even on higher API levels, not all magnifier features are supported on all platforms. To check whether a given MagnifierStyle is supported by the current platform, check the MagnifierStyle.isSupported property.

This function does not allow configuration of source bounds since the magnifier widget does not support constraining to the bounds of composables.

import androidx.compose.foundation.MagnifierStyle
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.magnifier
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.input.pointer.pointerInput

// When the magnifier center position is Unspecified, it is hidden.
// Hide the magnifier until a drag starts.
var magnifierCenter by remember { mutableStateOf(Offset.Unspecified) }

if (!MagnifierStyle.Default.isSupported) {
    Text("Magnifier is not supported on this platform.")
} else {
    Box(
        Modifier
            .magnifier(
                sourceCenter = { magnifierCenter },
                zoom = 2f
            )
            .pointerInput(Unit) {
                detectDragGestures(
                    // Show the magnifier at the original pointer position.
                    onDragStart = { magnifierCenter = it },
                    // Make the magnifier follow the finger while dragging.
                    onDrag = { _, delta -> magnifierCenter += delta },
                    // Hide the magnifier when the finger lifts.
                    onDragEnd = { magnifierCenter = Offset.Unspecified },
                    onDragCancel = { magnifierCenter = Offset.Unspecified }
                )
            }
            .drawBehind {
                // Some concentric circles to zoom in on.
                for (diameter in 2 until size.maxDimension.toInt() step 10) {
                    drawCircle(
                        color = Color.Black,
                        radius = diameter / 2f,
                        style = Stroke()
                    )
                }
            }
    )
}
Parameters
@ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> sourceCenter

The offset of the center of the magnified content. Measured in pixels from the top-left of the layout node this modifier is applied to. This offset is passed to Magnifier.show.

@ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull Offset> magnifierCenter

The offset of the magnifier widget itself, where the magnified content is rendered over the original content. Measured in density-independent pixels from the top-left of the layout node this modifier is applied to. If unspecified, the magnifier widget will be placed at a default offset relative to sourceCenter. The value of that offset is specified by the system.

float zoom

See Magnifier.setZoom. Not supported on SDK levels < Q.

@NonNull MagnifierStyle style

The MagnifierStyle to use to configure the magnifier widget.

Function1<@NonNull DpSizeUnit> onSizeChanged

An optional callback that will be invoked when the magnifier widget is initialized to report on its actual size. This can be useful if one of the default MagnifierStyles is used to find out what size the system decided to use for the widget.

ModifierLocalConsumerKt.modifierLocalConsumer

@ExperimentalComposeUiApi
default final @NonNull Modifier ModifierLocalConsumerKt.modifierLocalConsumer(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull ModifierLocalReadScopeUnit> consumer
)

A Modifier that can be used to consume ModifierLocals that were provided by other modifiers to the left of this modifier, or above this modifier in the layout tree.

ModifierLocalProviderKt.modifierLocalProvider

@ExperimentalComposeUiApi
default final @NonNull Modifier <T extends Object> ModifierLocalProviderKt.modifierLocalProvider(
    @NonNull Modifier receiver,
    @NonNull ProvidableModifierLocal<@NonNull T> key,
    @NonNull Function0<@NonNull T> value
)

A Modifier that can be used to provide ModifierLocals that can be read by other modifiers to the right of this modifier, or modifiers that are children of the layout node that this modifier is attached to.

NestedScrollModifierKt.nestedScroll

default final @NonNull Modifier NestedScrollModifierKt.nestedScroll(
    @NonNull Modifier receiver,
    @NonNull NestedScrollConnection connection,
    NestedScrollDispatcher dispatcher
)

Modify element to make it participate in the nested scrolling hierarchy.

There are two ways to participate in the nested scroll: as a scrolling child by dispatching scrolling events via NestedScrollDispatcher to the nested scroll chain; and as a member of nested scroll chain by providing NestedScrollConnection, which will be called when another nested scrolling child below dispatches scrolling events.

It's a mandatory to participate as a NestedScrollConnection in the chain, but scrolling events dispatch is optional since there are cases when element wants to participate in the nested scroll, but not a scrollable thing itself.

Here's the collapsing toolbar example that participates in a chain, but doesn't dispatch:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp

// here we use LazyColumn that has build-in nested scroll, but we want to act like a
// parent for this LazyColumn and participate in its nested scroll.
// Let's make a collapsing toolbar for LazyColumn
val toolbarHeight = 48.dp
val toolbarHeightPx = with(LocalDensity.current) { toolbarHeight.roundToPx().toFloat() }
// our offset to collapse toolbar
val toolbarOffsetHeightPx = remember { mutableStateOf(0f) }
// now, let's create connection to the nested scroll system and listen to the scroll
// happening inside child LazyColumn
val nestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
            // try to consume before LazyColumn to collapse toolbar if needed, hence pre-scroll
            val delta = available.y
            val newOffset = toolbarOffsetHeightPx.value + delta
            toolbarOffsetHeightPx.value = newOffset.coerceIn(-toolbarHeightPx, 0f)
            // here's the catch: let's pretend we consumed 0 in any case, since we want
            // LazyColumn to scroll anyway for good UX
            // We're basically watching scroll without taking it
            return Offset.Zero
        }
    }
}
Box(
    Modifier
        .fillMaxSize()
        // attach as a parent to the nested scroll system
        .nestedScroll(nestedScrollConnection)
) {
    // our list with build in nested scroll support that will notify us about its scroll
    LazyColumn(contentPadding = PaddingValues(top = toolbarHeight)) {
        items(100) { index ->
            Text("I'm item $index", modifier = Modifier.fillMaxWidth().padding(16.dp))
        }
    }
    TopAppBar(
        modifier = Modifier
            .height(toolbarHeight)
            .offset { IntOffset(x = 0, y = toolbarOffsetHeightPx.value.roundToInt()) },
        title = { Text("toolbar offset is ${toolbarOffsetHeightPx.value}") }
    )
}

On the other side, dispatch via NestedScrollDispatcher is optional. It's needed if a component is able to receive and react to the drag/fling events and you want this components to be able to notify parents when scroll occurs, resulting in better overall coordination.

Here's the example of the component that is draggable and dispatches nested scroll to participate in the nested scroll chain:

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp

// Let's take Modifier.draggable (which doesn't have nested scroll build in, unlike Modifier
// .scrollable) and add nested scroll support our component that contains draggable

// this will be a generic components that will work inside other nested scroll components.
// put it inside LazyColumn or / Modifier.verticalScroll to see how they will interact

// first, state and it's bounds
val basicState = remember { mutableStateOf(0f) }
val minBound = -100f
val maxBound = 100f
// lambda to update state and return amount consumed
val onNewDelta: (Float) -> Float = { delta ->
    val oldState = basicState.value
    val newState = (basicState.value + delta).coerceIn(minBound, maxBound)
    basicState.value = newState
    newState - oldState
}
// create a dispatcher to dispatch nested scroll events (participate like a nested scroll child)
val nestedScrollDispatcher = remember { NestedScrollDispatcher() }

// create nested scroll connection to react to nested scroll events (participate like a parent)
val nestedScrollConnection = remember {
    object : NestedScrollConnection {
        override fun onPostScroll(
            consumed: Offset,
            available: Offset,
            source: NestedScrollSource
        ): Offset {
            // we have no fling, so we're interested in the regular post scroll cycle
            // let's try to consume what's left if we need and return the amount consumed
            val vertical = available.y
            val weConsumed = onNewDelta(vertical)
            return Offset(x = 0f, y = weConsumed)
        }
    }
}
Box(
    Modifier
        .size(100.dp)
        .background(Color.LightGray)
        // attach ourselves to nested scroll system
        .nestedScroll(connection = nestedScrollConnection, dispatcher = nestedScrollDispatcher)
        .draggable(
            orientation = Orientation.Vertical,
            state = rememberDraggableState { delta ->
                // here's regular drag. Let's be good citizens and ask parents first if they
                // want to pre consume (it's a nested scroll contract)
                val parentsConsumed = nestedScrollDispatcher.dispatchPreScroll(
                    available = Offset(x = 0f, y = delta),
                    source = NestedScrollSource.Drag
                )
                // adjust what's available to us since might have consumed smth
                val adjustedAvailable = delta - parentsConsumed.y
                // we consume
                val weConsumed = onNewDelta(adjustedAvailable)
                // dispatch as a post scroll what's left after pre-scroll and our consumption
                val totalConsumed = Offset(x = 0f, y = weConsumed) + parentsConsumed
                val left = adjustedAvailable - weConsumed
                nestedScrollDispatcher.dispatchPostScroll(
                    consumed = totalConsumed,
                    available = Offset(x = 0f, y = left),
                    source = NestedScrollSource.Drag
                )
                // we won't dispatch pre/post fling events as we have no flinging here, but the
                // idea is very similar:
                // 1. dispatch pre fling, asking parents to pre consume
                // 2. fling (while dispatching scroll events like above for any fling tick)
                // 3. dispatch post fling, allowing parent to react to velocity left
            }
        )
) {
    Text(
        "State: ${basicState.value.roundToInt()}",
        modifier = Modifier.align(Alignment.Center)
    )
}

Note: It is recommended to reuse NestedScrollConnection and NestedScrollDispatcher objects between recompositions since different object will cause nested scroll graph to be recalculated unnecessary.

There are 4 main phases in nested scrolling system:

  1. Pre-scroll. This callback is triggered when the descendant is about to perform a scroll operation and gives parent an opportunity to consume part of child's delta beforehand. This pass should happen every time scrollable components receives delta and dispatches it via NestedScrollDispatcher. Dispatching child should take into account how much all ancestors above the hierarchy consumed and adjust the consumption accordingly.

  2. Post-scroll. This callback is triggered when the descendant consumed the delta already (after taking into account what parents pre-consumed in 1.) and wants to notify the ancestors with the amount of delta unconsumed. This pass should happen every time scrollable components receives delta and dispatches it via NestedScrollDispatcher. Any parent that receives NestedScrollConnection.onPostScroll should consume no more than left and return the amount consumed.

  3. Pre-fling. Pass that happens when the scrolling descendant stopped dragging and about to fling with the some velocity. This callback allows ancestors to consume part of the velocity. This pass should happen before the fling itself happens. Similar to pre-scroll, parent can consume part of the velocity and nodes below (including the dispatching child) should adjust their logic to accommodate only the velocity left.

  4. Post-fling. Pass that happens after the scrolling descendant stopped flinging and wants to notify ancestors about that fact, providing velocity left to consume as a part of this. This pass should happen after the fling itself happens on the scrolling child. Ancestors of the dispatching node will have opportunity to fling themselves with the velocityLeft provided. Parent must call notifySelfFinish callback in order to continue the propagation of the velocity that is left to ancestors above.

androidx.compose.foundation.lazy.LazyColumn, androidx.compose.foundation.verticalScroll and androidx.compose.foundation.gestures.scrollable have build in support for nested scrolling, however, it's desirable to be able to react and influence their scroll via nested scroll system.

Note: The nested scroll system is orientation independent. This mean it is based off the screen direction (x and y coordinates) rather than being locked to a specific orientation.

Parameters
@NonNull NestedScrollConnection connection

connection to the nested scroll system to participate in the event chaining, receiving events when scrollable descendant is being scrolled.

NestedScrollDispatcher dispatcher

object to be attached to the nested scroll system on which dispatch* methods can be called to notify ancestors within nested scroll system about scrolling happening

OffsetKt.absoluteOffset

default final @NonNull Modifier OffsetKt.absoluteOffset(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull IntOffset> offset
)

Offset the content by offset px. The offsets can be positive as well as non-positive. Applying an offset only changes the position of the content, without interfering with its size measurement.

This modifier is designed to be used for offsets that change, possibly due to user interactions. It avoids recomposition when the offset is changing, and also adds a graphics layer that prevents unnecessary redrawing of the context when the offset is changing.

This modifier will not consider layout direction when calculating the position of the content: a positive horizontal offset will always move the content to the right. For a modifier that considers layout direction when applying the offset, see offset.

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.offset
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp

// This text will be offset in steps of 10.dp from the top left of the available space.
var offset by remember { mutableStateOf(0) }
Text(
    "Layout offset modifier sample",
    Modifier
        .clickable { offset += 10 }
        .absoluteOffset { IntOffset(offset, offset) }
)
See also
absoluteOffset

Example usage:

OffsetKt.absoluteOffset

default final @NonNull Modifier OffsetKt.absoluteOffset(
    @NonNull Modifier receiver,
    @NonNull Dp x,
    @NonNull Dp y
)

Offset the content by (x dp, y dp). The offsets can be positive as well as non-positive. Applying an offset only changes the position of the content, without interfering with its size measurement.

This modifier will not consider layout direction when calculating the position of the content: a positive x offset will always move the content to the right. For a modifier that considers the layout direction when applying the offset, see offset.

import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

// This text will be offset (10.dp, 20.dp) from the center of the available space.
Text(
    "Layout offset modifier sample",
    Modifier.fillMaxSize()
        .wrapContentSize(Alignment.Center)
        .absoluteOffset(10.dp, 20.dp)
)
See also
offset

Example usage:

OffsetKt.offset

default final @NonNull Modifier OffsetKt.offset(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull Density, @NonNull IntOffset> offset
)

Offset the content by offset px. The offsets can be positive as well as non-positive. Applying an offset only changes the position of the content, without interfering with its size measurement.

This modifier is designed to be used for offsets that change, possibly due to user interactions. It avoids recomposition when the offset is changing, and also adds a graphics layer that prevents unnecessary redrawing of the context when the offset is changing.

This modifier will automatically adjust the horizontal offset according to the layout direction: when the LD is LTR, positive horizontal offsets will move the content to the right and when the LD is RTL, positive horizontal offsets will move the content to the left. For a modifier that offsets without considering layout direction, see absoluteOffset.

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.offset
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp

// This text will be offset in steps of 10.dp from the top left of the available space in
// left-to-right context, and from top right in right-to-left context.
var offset by remember { mutableStateOf(0) }
Text(
    "Layout offset modifier sample",
    Modifier
        .clickable { offset += 10 }
        .offset { IntOffset(offset, offset) }
)
See also
absoluteOffset

Example usage:

OffsetKt.offset

default final @NonNull Modifier OffsetKt.offset(@NonNull Modifier receiver, @NonNull Dp x, @NonNull Dp y)

Offset the content by (x dp, y dp). The offsets can be positive as well as non-positive. Applying an offset only changes the position of the content, without interfering with its size measurement.

This modifier will automatically adjust the horizontal offset according to the layout direction: when the layout direction is LTR, positive x offsets will move the content to the right and when the layout direction is RTL, positive x offsets will move the content to the left. For a modifier that offsets without considering layout direction, see absoluteOffset.

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

// This text will be offset (10.dp, 20.dp) from the center of the available space. In the
// right-to-left context, the offset will be (-10.dp, 20.dp).
Text(
    "Layout offset modifier sample",
    Modifier.fillMaxSize()
        .wrapContentSize(Alignment.Center)
        .offset(10.dp, 20.dp)
)
See also
absoluteOffset

Example usage:

OnGloballyPositionedModifierKt.onGloballyPositioned

default final @NonNull Modifier OnGloballyPositionedModifierKt.onGloballyPositioned(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinatesUnit> onGloballyPositioned
)

Invoke onGloballyPositioned with the LayoutCoordinates of the element when the global position of the content may have changed. Note that it will be called after a composition when the coordinates are finalized.

This callback will be invoked at least once when the LayoutCoordinates are available, and every time the element's position changes within the window. However, it is not guaranteed to be invoked every time the position relative to the screen of the modified element changes. For example, the system may move the contents inside a window around without firing a callback. If you are using the LayoutCoordinates to calculate position on the screen, and not just inside the window, you may not receive a callback.

Usage example:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.unit.dp

Column(
    Modifier.onGloballyPositioned { coordinates ->
        // This will be the size of the Column.
        coordinates.size
        // The position of the Column relative to the application window.
        coordinates.positionInWindow()
        // The position of the Column relative to the Compose root.
        coordinates.positionInRoot()
        // These will be the alignment lines provided to the layout (empty here for Column).
        coordinates.providedAlignmentLines
        // This will be a LayoutCoordinates instance corresponding to the parent of Column.
        coordinates.parentLayoutCoordinates
    }
) {
    Box(Modifier.size(20.dp).background(Color.Green))
    Box(Modifier.size(20.dp).background(Color.Blue))
}

OnPlacedModifierKt.onPlaced

default final @NonNull Modifier OnPlacedModifierKt.onPlaced(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinatesUnit> onPlaced
)

Invoke onPlaced after the parent LayoutModifier and parent layout has been placed and before child LayoutModifier is placed. This allows child LayoutModifier to adjust its own placement based on where the parent is.

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationVector2D
import androidx.compose.animation.core.Spring.StiffnessMediumLow
import androidx.compose.animation.core.VectorConverter
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round

@OptIn(ExperimentalComposeUiApi::class)
fun Modifier.animatePlacement(): Modifier = composed {
    val scope = rememberCoroutineScope()
    var targetOffset by remember { mutableStateOf(IntOffset.Zero) }
    var animatable by remember {
        mutableStateOf<Animatable<IntOffset, AnimationVector2D>?>(null)
    }
    this.onPlaced {
        // Calculate the position in the parent layout
        targetOffset = it.positionInParent().round()
    }.offset {
        // Animate to the new target offset when alignment changes.
        val anim = animatable ?: Animatable(targetOffset, IntOffset.VectorConverter)
            .also { animatable = it }
        if (anim.targetValue != targetOffset) {
            scope.launch {
                anim.animateTo(targetOffset, spring(stiffness = StiffnessMediumLow))
            }
        }
        // Offset the child in the opposite direction to the targetOffset, and slowly catch
        // up to zero offset via an animation to achieve an overall animated movement.
        animatable?.let { it.value - targetOffset } ?: IntOffset.Zero
    }
}

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun AnimatedChildAlignment(alignment: Alignment) {
    Box(
        Modifier.fillMaxSize().padding(4.dp).border(1.dp, Color.Red)
    ) {
        Box(
            modifier = Modifier.animatePlacement().align(alignment).size(100.dp)
                .background(Color.Red)
        )
    }
}

OnRemeasuredModifierKt.onSizeChanged

default final @NonNull Modifier OnRemeasuredModifierKt.onSizeChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull IntSizeUnit> onSizeChanged
)

Invoked with the size of the modified Compose UI element when the element is first measured or when the size of the element changes.

There are no guarantees onSizeChanged will not be re-invoked with the same size.

Using the onSizeChanged size value in a MutableState to update layout causes the new size value to be read and the layout to be recomposed in the succeeding frame, resulting in a one frame lag.

You can use onSizeChanged to affect drawing operations. Use Layout or SubcomposeLayout to enable the size of one component to affect the size of another.

Example usage:

import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged

// Use onSizeChanged() for diagnostics. Use Layout or SubcomposeLayout if you want
// to use the size of one component to affect the size of another component.
Text(
    "Hello $name",
    Modifier.onSizeChanged { size ->
        println("The size of the Text in pixels is $size")
    }
)

OverscrollKt.overscroll

@ExperimentalFoundationApi
default final @NonNull Modifier OverscrollKt.overscroll(
    @NonNull Modifier receiver,
    @NonNull OverscrollEffect overscrollEffect
)

Renders overscroll from the provided overscrollEffect.

This modifier is a convenience method to call OverscrollEffect.effectModifier, which renders the actual effect. Note that this modifier is only responsible for the visual part of overscroll - on its own it will not handle input events. In addition to using this modifier you also need to propagate events to the overscrollEffect, most commonly by using a androidx.compose.foundation.gestures.scrollable.

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.spring
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.OverscrollEffect
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.overscroll
import androidx.compose.material.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@OptIn(ExperimentalFoundationApi::class)
// our custom offset overscroll that offset the element it is applied to when we hit the bound
// on the scrollable container.
class OffsetOverscrollEffect(val scope: CoroutineScope) : OverscrollEffect {
    private val overscrollOffset = Animatable(0f)

    override fun applyToScroll(
        delta: Offset,
        source: NestedScrollSource,
        performScroll: (Offset) -> Offset
    ): Offset {
        // in pre scroll we relax the overscroll if needed
        // relaxation: when we are in progress of the overscroll and user scrolls in the
        // different direction = substract the overscroll first
        val sameDirection = sign(delta.y) == sign(overscrollOffset.value)
        val consumedByPreScroll = if (abs(overscrollOffset.value) > 0.5 && !sameDirection) {
            val prevOverscrollValue = overscrollOffset.value
            val newOverscrollValue = overscrollOffset.value + delta.y
            if (sign(prevOverscrollValue) != sign(newOverscrollValue)) {
                // sign changed, coerce to start scrolling and exit
                scope.launch { overscrollOffset.snapTo(0f) }
                Offset(x = 0f, y = delta.y + prevOverscrollValue)
            } else {
                scope.launch {
                    overscrollOffset.snapTo(overscrollOffset.value + delta.y)
                }
                delta.copy(x = 0f)
            }
        } else {
            Offset.Zero
        }
        val leftForScroll = delta - consumedByPreScroll
        val consumedByScroll = performScroll(leftForScroll)
        val overscrollDelta = leftForScroll - consumedByScroll
        // if it is a drag, not a fling, add the delta left to our over scroll value
        if (abs(overscrollDelta.y) > 0.5 && source == NestedScrollSource.Drag) {
            scope.launch {
                // multiply by 0.1 for the sake of parallax effect
                overscrollOffset.snapTo(overscrollOffset.value + overscrollDelta.y * 0.1f)
            }
        }
        return consumedByPreScroll + consumedByScroll
    }

    override suspend fun applyToFling(
        velocity: Velocity,
        performFling: suspend (Velocity) -> Velocity
    ) {
        val consumed = performFling(velocity)
        // when the fling happens - we just gradually animate our overscroll to 0
        val remaining = velocity - consumed
        overscrollOffset.animateTo(
            targetValue = 0f,
            initialVelocity = remaining.y,
            animationSpec = spring()
        )
    }

    override val isInProgress: Boolean
        get() = overscrollOffset.value != 0f

    // as we're building an offset modifiers, let's offset of our value we calculated
    override val effectModifier: Modifier = Modifier.offset {
        IntOffset(x = 0, y = overscrollOffset.value.roundToInt())
    }
}

val offset = remember { mutableStateOf(0f) }
val scope = rememberCoroutineScope()
// Create the overscroll controller
val overscroll = remember(scope) { OffsetOverscrollEffect(scope) }
// let's build a scrollable that scroll until -512 to 512
val scrollStateRange = (-512f).rangeTo(512f)
Box(
    Modifier
        .size(150.dp)
        .scrollable(
            orientation = Orientation.Vertical,
            state = rememberScrollableState { delta ->
                // use the scroll data and indicate how much this element consumed.
                val oldValue = offset.value
                // coerce to our range
                offset.value = (offset.value + delta).coerceIn(scrollStateRange)

                offset.value - oldValue // indicate that we consumed what's needed
            },
            // pass the overscroll to the scrollable so the data is updated
            overscrollEffect = overscroll
        )
        .background(Color.LightGray),
    contentAlignment = Alignment.Center
) {
    Text(
        offset.value.roundToInt().toString(),
        style = TextStyle(fontSize = 32.sp),
        modifier = Modifier
            // show the overscroll only on the text, not the containers (just for fun)
            .overscroll(overscroll)
    )
}
Parameters
@NonNull OverscrollEffect overscrollEffect

the OverscrollEffect to render

PaddingKt.absolutePadding

default final @NonNull Modifier PaddingKt.absolutePadding(
    @NonNull Modifier receiver,
    @NonNull Dp left,
    @NonNull Dp top,
    @NonNull Dp right,
    @NonNull Dp bottom
)

Apply additional space along each edge of the content in Dp: left, top, right and bottom. These paddings are applied without regard to the current LayoutDirection, see padding to apply relative paddings. Padding is applied before content measurement and takes precedence; content may only be as large as the remaining space.

Negative padding is not permitted — it will cause IllegalArgumentException. See Modifier.offset.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.absolutePadding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.background(color = Color.Gray)) {
    Box(
        Modifier.absolutePadding(left = 20.dp, top = 30.dp, right = 20.dp, bottom = 30.dp)
            .size(50.dp)
            .background(Color.Blue)
    )
}

PaddingKt.padding

default final @NonNull Modifier PaddingKt.padding(@NonNull Modifier receiver, @NonNull Dp all)

Apply all dp of additional space along each edge of the content, left, top, right and bottom. Padding is applied before content measurement and takes precedence; content may only be as large as the remaining space.

Negative padding is not permitted — it will cause IllegalArgumentException. See Modifier.offset.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.background(color = Color.Gray)) {
    Box(Modifier.padding(all = 20.dp).size(50.dp).background(Color.Blue))
}

PaddingKt.padding

default final @NonNull Modifier PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull PaddingValues paddingValues
)

Apply PaddingValues to the component as additional space along each edge of the content's left, top, right and bottom. Padding is applied before content measurement and takes precedence; content may only be as large as the remaining space.

Negative padding is not permitted — it will cause IllegalArgumentException. See Modifier.offset.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val innerPadding = PaddingValues(top = 10.dp, start = 15.dp)
Box(Modifier.background(color = Color.Gray)) {
    Box(Modifier.padding(innerPadding).size(50.dp).background(Color.Blue))
}

PaddingKt.padding

default final @NonNull Modifier PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull Dp horizontal,
    @NonNull Dp vertical
)

Apply horizontal dp space along the left and right edges of the content, and vertical dp space along the top and bottom edges. Padding is applied before content measurement and takes precedence; content may only be as large as the remaining space.

Negative padding is not permitted — it will cause IllegalArgumentException. See Modifier.offset.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.background(color = Color.Gray)) {
    Box(
        Modifier
            .padding(horizontal = 20.dp, vertical = 30.dp)
            .size(50.dp)
            .background(Color.Blue)
    )
}

PaddingKt.padding

default final @NonNull Modifier PaddingKt.padding(
    @NonNull Modifier receiver,
    @NonNull Dp start,
    @NonNull Dp top,
    @NonNull Dp end,
    @NonNull Dp bottom
)

Apply additional space along each edge of the content in Dp: start, top, end and bottom. The start and end edges will be determined by the current LayoutDirection. Padding is applied before content measurement and takes precedence; content may only be as large as the remaining space.

Negative padding is not permitted — it will cause IllegalArgumentException. See Modifier.offset.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.background(color = Color.Gray)) {
    Box(
        Modifier.padding(start = 20.dp, top = 30.dp, end = 20.dp, bottom = 30.dp)
            .size(50.dp)
            .background(Color.Blue)
    )
}

PainterModifierKt.paint

default final @NonNull Modifier PainterModifierKt.paint(
    @NonNull Modifier receiver,
    @NonNull Painter painter,
    boolean sizeToIntrinsics,
    @NonNull Alignment alignment,
    @NonNull ContentScale contentScale,
    float alpha,
    ColorFilter colorFilter
)

Paint the content using painter.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.unit.dp

class CustomPainter : Painter() {

    override val intrinsicSize: Size
        get() = Size(300.0f, 300.0f)

    override fun DrawScope.onDraw() {
        drawCircle(
            center = center,
            radius = size.minDimension / 2.0f,
            color = Color.Red
        )
    }
}

Box(
    modifier =
        Modifier.background(color = Color.Gray)
            .padding(30.dp)
            .background(color = Color.Yellow)
            .paint(CustomPainter())
) { /** intentionally empty **/ }
Parameters
boolean sizeToIntrinsics

true to size the element relative to Painter.intrinsicSize

@NonNull Alignment alignment

specifies alignment of the painter relative to content

@NonNull ContentScale contentScale

strategy for scaling painter if its size does not match the content size

float alpha

opacity of painter

ColorFilter colorFilter

optional ColorFilter to apply to painter

PointerIconKt.pointerHoverIcon

default final @NonNull Modifier PointerIconKt.pointerHoverIcon(
    @NonNull Modifier receiver,
    @NonNull PointerIcon icon,
    boolean overrideDescendants
)

Modifier that lets a developer define a pointer icon to display when the cursor is hovered over the element. When overrideDescendants is set to true, children cannot override the pointer icon using this modifier.

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.PointerIcon
import androidx.compose.ui.input.pointer.pointerHoverIcon

Column(Modifier.pointerHoverIcon(PointerIcon.Crosshair)) {
    SelectionContainer {
        Column {
            Text("Selectable text")
            Text(
                modifier = Modifier.pointerHoverIcon(PointerIcon.Hand, true),
                text = "Selectable text with hand"
            )
        }
    }
    Text("Just text with global pointerIcon")
}
Parameters
@NonNull PointerIcon icon

The icon to set

boolean overrideDescendants

when false (by default) descendants are able to set their own pointer icon. If true, all children under this parent will receive the requested pointer icon and are no longer allowed to override their own pointer icon.

PointerInteropFilterKt.motionEventSpy

default final @NonNull Modifier PointerInteropFilterKt.motionEventSpy(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull MotionEventUnit> watcher
)

Calls watcher with each MotionEvent that the layout area or any child pointerInput receives. The MotionEvent may or may not have been transformed to the local coordinate system. The Compose View will be considered as handling the MotionEvent in the area that the motionEventSpy is active.

This method can only be used to observe MotionEvents and can not be used to capture an event stream.

watcher is called during the PointerEventPass.Initial pass.

Developers should use pointerInput to handle pointer input processing within Compose. motionEventSpy is only useful as part of Android View interoperability.

PointerInteropFilterKt.pointerInteropFilter

@ExperimentalComposeUiApi
default final @NonNull Modifier PointerInteropFilterKt.pointerInteropFilter(
    @NonNull Modifier receiver,
    RequestDisallowInterceptTouchEvent requestDisallowInterceptTouchEvent,
    @NonNull Function1<@NonNull MotionEvent, @NonNull Boolean> onTouchEvent
)

A special PointerInputModifier that provides access to the underlying MotionEvents originally dispatched to Compose. Prefer pointerInput and use this only for interoperation with existing code that consumes MotionEvents.

While the main intent of this Modifier is to allow arbitrary code to access the original MotionEvent dispatched to Compose, for completeness, analogs are provided to allow arbitrary code to interact with the system as if it were an Android View.

This includes 2 APIs,

  1. onTouchEvent has a Boolean return type which is akin to the return type of View.onTouchEvent. If the provided onTouchEvent returns true, it will continue to receive the event stream (unless the event stream has been intercepted) and if it returns false, it will not.

  2. requestDisallowInterceptTouchEvent is a lambda that you can optionally provide so that you can later call it (yes, in this case, you call the lambda that you provided) which is akin to calling ViewParent.requestDisallowInterceptTouchEvent. When this is called, any associated ancestors in the tree that abide by the contract will act accordingly and will not intercept the even stream.

ProgressSemanticsKt.progressSemantics

default final @NonNull Modifier ProgressSemanticsKt.progressSemantics(@NonNull Modifier receiver)

Contains the semantics required for an indeterminate progress indicator, that represents the fact of the in-progress operation.

If you need determinate progress 0.0 to 1.0, consider using overload with the progress parameter.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.progressSemantics
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color

Box(Modifier.progressSemantics().background(color = Color.Cyan)) {
    Text("Operation is on progress")
}

ProgressSemanticsKt.progressSemantics

default final @NonNull Modifier ProgressSemanticsKt.progressSemantics(
    @NonNull Modifier receiver,
    float value,
    @NonNull ClosedFloatingPointRange<@NonNull Float> valueRange,
    int steps
)

Contains the semantics required for a determinate progress indicator or the progress part of a slider, that represents progress within valueRange. value outside of this range will be coerced into this range.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.progressSemantics
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val progress = 0.5f // emulate progress from some state
Box(
    Modifier
        .progressSemantics(progress)
        .size((progress * 100).dp, 4.dp)
        .background(color = Color.Cyan)
)
Parameters
float value

current value of the ProgressIndicator/Slider. If outside of valueRange provided, value will be coerced to this range. Must not be NaN.

@NonNull ClosedFloatingPointRange<@NonNull Float> valueRange

range of values that value can take. Passed value will be coerced to this range

int steps

if greater than 0, specifies the amounts of discrete values, evenly distributed between across the whole value range. If 0, any value from the range specified is allowed. Must not be negative.

RelocationRequesterModifierKt.relocationRequester

@ExperimentalComposeUiApi
default final @NonNull Modifier RelocationRequesterModifierKt.relocationRequester(
    @NonNull Modifier receiver,
    @NonNull Object relocationRequester
)

This is a modifier that can be used to send relocation requests.

Parameters
@NonNull Object relocationRequester

an instance of RelocationRequester. This hoisted object can be used to send relocation requests to parents of the current composable.

RotaryInputModifierKt.onPreRotaryScrollEvent

default final @NonNull Modifier RotaryInputModifierKt.onPreRotaryScrollEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onPreRotaryScrollEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept RotaryScrollEvents if it (or one of its children) is focused.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.material.darkColors
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.input.rotary.onPreRotaryScrollEvent
import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp

MaterialTheme(colors = darkColors()) {
    val rowScrollState = rememberScrollState()
    val columnScrollState = rememberScrollState()
    val coroutineScope = rememberCoroutineScope()
    val focusRequester = remember { FocusRequester() }
    var interceptScroll by remember { mutableStateOf(false) }
    Column(
        Modifier
            .onPreRotaryScrollEvent {
                // You can intercept an event before it is sent to the child.
                if (interceptScroll) {
                    coroutineScope.launch {
                        rowScrollState.scrollBy(it.horizontalScrollPixels)
                    }
                    // return true to consume this event.
                    true
                } else {
                    // return false to ignore this event and continue propagation to the child.
                    false
                }
            }
            .onRotaryScrollEvent {
                // If the child does not use the scroll, we get notified here.
                coroutineScope.launch {
                    rowScrollState.scrollBy(it.horizontalScrollPixels)
                }
                true
            }
    ) {
        Row(
            modifier = Modifier.align(CenterHorizontally),
            verticalAlignment = CenterVertically
        ) {
            Text(
                modifier = Modifier.width(70.dp),
                text = if (interceptScroll) "Row" else "Column",
                style = TextStyle(color = White)
            )
            Switch(
                checked = interceptScroll,
                onCheckedChange = { interceptScroll = it },
            )
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rowScrollState)
        ) {
            repeat(100) {
                Text(
                    text = "row item $it ",
                    modifier = Modifier.align(CenterVertically),
                    color = White,
                )
            }
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(columnScrollState)
                .onRotaryScrollEvent {
                    coroutineScope.launch {
                        columnScrollState.scrollBy(it.verticalScrollPixels)
                    }
                    true
                }
                .focusRequester(focusRequester)
                .focusable(),
        ) {
            repeat(100) {
                Text(
                    text = "column item $it",
                    modifier = Modifier.align(CenterHorizontally),
                    color = White,
                )
            }
        }
    }

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}
Parameters
@NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onPreRotaryScrollEvent

This callback is invoked when the user interacts with the rotary button on a wear device. It gives ancestors of a focused component the chance to intercept a RotaryScrollEvent.

When the user rotates the side button on a wear device, a RotaryScrollEvent is sent to the focused item. Before reaching the focused item, this event starts at the root composable, and propagates down the hierarchy towards the focused item. It invokes any onPreRotaryScrollEvents it encounters on ancestors of the focused item. After reaching the focused item, the event propagates up the hierarchy back towards the parent. It invokes any onRotaryScrollEvents it encounters on its way back.

Return true to indicate that you consumed the event and want to stop propagation of this event.

Returns
@NonNull Modifier

true if the event is consumed, false otherwise.

RotaryInputModifierKt.onRotaryScrollEvent

default final @NonNull Modifier RotaryInputModifierKt.onRotaryScrollEvent(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onRotaryScrollEvent
)

Adding this modifier to the modifier parameter of a component will allow it to intercept RotaryScrollEvents if it (or one of its children) is focused.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.input.rotary.onRotaryScrollEvent

val scrollState = rememberScrollState()
val coroutineScope = rememberCoroutineScope()
val focusRequester = remember { FocusRequester() }
Column(
    modifier = Modifier
        .fillMaxWidth()
        .verticalScroll(scrollState)
        .onRotaryScrollEvent {
            coroutineScope.launch {
                scrollState.scrollTo((scrollState.value +
                    it.verticalScrollPixels).roundToInt())
            }
            true
        }
        .focusRequester(focusRequester)
        .focusable(),
) {
    repeat(100) {
        Text(
            text = "item $it",
            modifier = Modifier.align(CenterHorizontally),
            color = White,
        )
    }
}

LaunchedEffect(Unit) {
    focusRequester.requestFocus()
}

This sample demonstrates how a parent can add an onRotaryScrollEvent modifier to gain access to a RotaryScrollEvent when a child does not consume it:

import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Switch
import androidx.compose.material.Text
import androidx.compose.material.darkColors
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.input.rotary.onPreRotaryScrollEvent
import androidx.compose.ui.input.rotary.onRotaryScrollEvent
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp

MaterialTheme(colors = darkColors()) {
    val rowScrollState = rememberScrollState()
    val columnScrollState = rememberScrollState()
    val coroutineScope = rememberCoroutineScope()
    val focusRequester = remember { FocusRequester() }
    var interceptScroll by remember { mutableStateOf(false) }
    Column(
        Modifier
            .onPreRotaryScrollEvent {
                // You can intercept an event before it is sent to the child.
                if (interceptScroll) {
                    coroutineScope.launch {
                        rowScrollState.scrollBy(it.horizontalScrollPixels)
                    }
                    // return true to consume this event.
                    true
                } else {
                    // return false to ignore this event and continue propagation to the child.
                    false
                }
            }
            .onRotaryScrollEvent {
                // If the child does not use the scroll, we get notified here.
                coroutineScope.launch {
                    rowScrollState.scrollBy(it.horizontalScrollPixels)
                }
                true
            }
    ) {
        Row(
            modifier = Modifier.align(CenterHorizontally),
            verticalAlignment = CenterVertically
        ) {
            Text(
                modifier = Modifier.width(70.dp),
                text = if (interceptScroll) "Row" else "Column",
                style = TextStyle(color = White)
            )
            Switch(
                checked = interceptScroll,
                onCheckedChange = { interceptScroll = it },
            )
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .horizontalScroll(rowScrollState)
        ) {
            repeat(100) {
                Text(
                    text = "row item $it ",
                    modifier = Modifier.align(CenterVertically),
                    color = White,
                )
            }
        }
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(columnScrollState)
                .onRotaryScrollEvent {
                    coroutineScope.launch {
                        columnScrollState.scrollBy(it.verticalScrollPixels)
                    }
                    true
                }
                .focusRequester(focusRequester)
                .focusable(),
        ) {
            repeat(100) {
                Text(
                    text = "column item $it",
                    modifier = Modifier.align(CenterHorizontally),
                    color = White,
                )
            }
        }
    }

    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}
Parameters
@NonNull Function1<@NonNull RotaryScrollEvent, @NonNull Boolean> onRotaryScrollEvent

This callback is invoked when the user interacts with the rotary side button or the bezel on a wear device. While implementing this callback, return true to stop propagation of this event. If you return false, the event will be sent to this onRotaryScrollEvent's parent.

Returns
@NonNull Modifier

true if the event is consumed, false otherwise.

Here is an example of a scrollable container that scrolls in response to RotaryScrollEvents.

RotateKt.rotate

default final @NonNull Modifier RotateKt.rotate(@NonNull Modifier receiver, float degrees)

Sets the degrees the view is rotated around the center of the composable. Increasing values result in clockwise rotation. Negative degrees are used to rotate in the counter clockwise direction

Usage of this API renders this composable into a separate graphics layer.

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.unit.dp

Box(
    Modifier.rotate(45f)
        .size(100.dp, 100.dp)
)
See also
graphicsLayer

Example usage:

ScaleKt.scale

default final @NonNull Modifier ScaleKt.scale(@NonNull Modifier receiver, float scale)

Scale the contents of both the horizontal and vertical axis uniformly by the same scale factor.

Usage of this API renders this composable into a separate graphics layer

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.unit.dp

Box(
    Modifier.scale(2f)
        .size(100.dp, 100.dp)
)
Parameters
float scale

Multiplier to scale content along the horizontal and vertical axis

See also
graphicsLayer

Example usage:

ScaleKt.scale

default final @NonNull Modifier ScaleKt.scale(@NonNull Modifier receiver, float scaleX, float scaleY)

Scale the contents of the composable by the following scale factors along the horizontal and vertical axis respectively. Negative scale factors can be used to mirror content across the corresponding horizontal or vertical axis.

Example usage:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.unit.dp

Box(
    Modifier.scale(scaleX = 2f, scaleY = 3f)
        .size(100.dp, 100.dp)
)

Usage of this API renders this composable into a separate graphics layer

Parameters
float scaleX

Multiplier to scale content along the horizontal axis

float scaleY

Multiplier to scale content along the vertical axis

See also
graphicsLayer

ScrollKt.horizontalScroll

default final @NonNull Modifier ScrollKt.horizontalScroll(
    @NonNull Modifier receiver,
    @NonNull ScrollState state,
    boolean enabled,
    FlingBehavior flingBehavior,
    boolean reverseScrolling
)

Modify element to allow to scroll horizontally when width of the content is bigger than max constraints allow.

import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.dp

val scrollState = rememberScrollState()
val gradient = Brush.horizontalGradient(
    listOf(Color.Red, Color.Blue, Color.Green), 0.0f, 10000.0f, TileMode.Repeated
)
Box(
    Modifier
        .horizontalScroll(scrollState)
        .size(width = 10000.dp, height = 200.dp)
        .background(brush = gradient)
)

In order to use this modifier, you need to create and own ScrollState

Parameters
@NonNull ScrollState state

state of the scroll

boolean enabled

whether or not scrolling via touch input is enabled

FlingBehavior flingBehavior

logic describing fling behavior when drag has finished with velocity. If null, default from ScrollableDefaults.flingBehavior will be used.

boolean reverseScrolling

reverse the direction of scrolling, when true, 0 ScrollState.value will mean right, when false, 0 ScrollState.value will mean left

ScrollKt.verticalScroll

default final @NonNull Modifier ScrollKt.verticalScroll(
    @NonNull Modifier receiver,
    @NonNull ScrollState state,
    boolean enabled,
    FlingBehavior flingBehavior,
    boolean reverseScrolling
)

Modify element to allow to scroll vertically when height of the content is bigger than max constraints allow.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.TileMode
import androidx.compose.ui.unit.dp

val scrollState = rememberScrollState()
val gradient = Brush.verticalGradient(
    listOf(Color.Red, Color.Blue, Color.Green), 0.0f, 10000.0f, TileMode.Repeated
)
Box(
    Modifier
        .verticalScroll(scrollState)
        .fillMaxWidth()
        .requiredHeight(10000.dp)
        .background(brush = gradient)
)

In order to use this modifier, you need to create and own ScrollState

Parameters
@NonNull ScrollState state

state of the scroll

boolean enabled

whether or not scrolling via touch input is enabled

FlingBehavior flingBehavior

logic describing fling behavior when drag has finished with velocity. If null, default from ScrollableDefaults.flingBehavior will be used.

boolean reverseScrolling

reverse the direction of scrolling, when true, 0 ScrollState.value will mean bottom, when false, 0 ScrollState.value will mean top

ScrollableKt.scrollable

default final @NonNull Modifier ScrollableKt.scrollable(
    @NonNull Modifier receiver,
    @NonNull ScrollableState state,
    @NonNull Orientation orientation,
    boolean enabled,
    boolean reverseDirection,
    FlingBehavior flingBehavior,
    MutableInteractionSource interactionSource
)

Configure touch scrolling and flinging for the UI element in a single Orientation.

Users should update their state themselves using default ScrollableState and its consumeScrollDelta callback or by implementing ScrollableState interface manually and reflect their own state in UI when using this component.

If you don't need to have fling or nested scroll support, but want to make component simply draggable, consider using draggable.

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// actual composable state that we will show on UI and update in `Scrollable`
val offset = remember { mutableStateOf(0f) }
Box(
    Modifier
        .size(150.dp)
        .scrollable(
            orientation = Orientation.Vertical,
            // state for Scrollable, describes how consume scroll amount
            state = rememberScrollableState { delta ->
                // use the scroll data and indicate how much this element consumed.
                // unconsumed deltas will be propagated to nested scrollables (if present)
                offset.value = offset.value + delta // update the state
                delta // indicate that we consumed all the pixels available
            }
        )
        .background(Color.LightGray),
    contentAlignment = Alignment.Center
) {
    // Modifier.scrollable is not opinionated about its children's layouts. It will however
    // promote nested scrolling capabilities if those children also use the modifier.
    // The modifier will not change any layouts so one must handle any desired changes through
    // the delta values in the scrollable state
    Text(offset.value.roundToInt().toString(), style = TextStyle(fontSize = 32.sp))
}
Parameters
@NonNull ScrollableState state

ScrollableState state of the scrollable. Defines how scroll events will be interpreted by the user land logic and contains useful information about on-going events.

@NonNull Orientation orientation

orientation of the scrolling

boolean enabled

whether or not scrolling in enabled

boolean reverseDirection

reverse the direction of the scroll, so top to bottom scroll will behave like bottom to top and left to right will behave like right to left.

FlingBehavior flingBehavior

logic describing fling behavior when drag has finished with velocity. If null, default from ScrollableDefaults.flingBehavior will be used.

MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit drag events when this scrollable is being dragged.

ScrollableKt.scrollable

@ExperimentalFoundationApi
default final @NonNull Modifier ScrollableKt.scrollable(
    @NonNull Modifier receiver,
    @NonNull ScrollableState state,
    @NonNull Orientation orientation,
    OverscrollEffect overscrollEffect,
    boolean enabled,
    boolean reverseDirection,
    FlingBehavior flingBehavior,
    MutableInteractionSource interactionSource
)

Configure touch scrolling and flinging for the UI element in a single Orientation.

Users should update their state themselves using default ScrollableState and its consumeScrollDelta callback or by implementing ScrollableState interface manually and reflect their own state in UI when using this component.

If you don't need to have fling or nested scroll support, but want to make component simply draggable, consider using draggable.

This overload provides the access to OverscrollEffect that defines the behaviour of the over scrolling logic. Consider using ScrollableDefaults.overscrollEffect for the platform look-and-feel.

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberScrollableState
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

// actual composable state that we will show on UI and update in `Scrollable`
val offset = remember { mutableStateOf(0f) }
Box(
    Modifier
        .size(150.dp)
        .scrollable(
            orientation = Orientation.Vertical,
            // state for Scrollable, describes how consume scroll amount
            state = rememberScrollableState { delta ->
                // use the scroll data and indicate how much this element consumed.
                // unconsumed deltas will be propagated to nested scrollables (if present)
                offset.value = offset.value + delta // update the state
                delta // indicate that we consumed all the pixels available
            }
        )
        .background(Color.LightGray),
    contentAlignment = Alignment.Center
) {
    // Modifier.scrollable is not opinionated about its children's layouts. It will however
    // promote nested scrolling capabilities if those children also use the modifier.
    // The modifier will not change any layouts so one must handle any desired changes through
    // the delta values in the scrollable state
    Text(offset.value.roundToInt().toString(), style = TextStyle(fontSize = 32.sp))
}
Parameters
@NonNull ScrollableState state

ScrollableState state of the scrollable. Defines how scroll events will be interpreted by the user land logic and contains useful information about on-going events.

@NonNull Orientation orientation

orientation of the scrolling

OverscrollEffect overscrollEffect

effect to which the deltas will be fed when the scrollable have some scrolling delta left. Pass null for no overscroll. If you pass an effect you should also apply androidx.compose.foundation.overscroll modifier.

boolean enabled

whether or not scrolling in enabled

boolean reverseDirection

reverse the direction of the scroll, so top to bottom scroll will behave like bottom to top and left to right will behave like right to left.

FlingBehavior flingBehavior

logic describing fling behavior when drag has finished with velocity. If null, default from ScrollableDefaults.flingBehavior will be used.

MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit drag events when this scrollable is being dragged.

SelectableGroupKt.selectableGroup

default final @NonNull Modifier SelectableGroupKt.selectableGroup(@NonNull Modifier receiver)

Use this modifier to group a list of selectable items like Tabs or RadioButtons together for accessibility purpose.

See also
selectableGroup

SelectableKt.selectable

default final @NonNull Modifier SelectableKt.selectable(
    @NonNull Modifier receiver,
    boolean selected,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to be selectable, usually as a part of a mutually exclusive group, where only one item can be selected at any point in time. A typical example of mutually exclusive set is a RadioGroup or a row of Tabs. To ensure correct accessibility behavior, make sure to pass Modifier.selectableGroup modifier into the RadioGroup or the row.

If you want to make an item support on/off capabilities without being part of a set, consider using Modifier.toggleable

This version has no MutableInteractionSource or Indication parameters, default indication from LocalIndication will be used. To specify MutableInteractionSource or Indication, use another overload.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val option1 = Color.Red
val option2 = Color.Blue
var selectedOption by remember { mutableStateOf(option1) }
Column {
    Text("Selected: $selectedOption")
    Row {
        listOf(option1, option2).forEach { color ->
            val selected = selectedOption == color
            Box(
                Modifier
                    .size(100.dp)
                    .background(color = color)
                    .selectable(
                        selected = selected,
                        onClick = { selectedOption = color }
                    )
            )
        }
    }
}
Parameters
boolean selected

whether or not this item is selected in a mutually exclusion set

boolean enabled

whether or not this selectable will handle input events and appear enabled from a semantics perspective

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

callback to invoke when this item is clicked

SelectableKt.selectable

default final @NonNull Modifier SelectableKt.selectable(
    @NonNull Modifier receiver,
    boolean selected,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to be selectable, usually as a part of a mutually exclusive group, where only one item can be selected at any point in time. A typical example of mutually exclusive set is a RadioGroup or a row of Tabs. To ensure correct accessibility behavior, make sure to pass Modifier.selectableGroup modifier into the RadioGroup or the row.

If you want to make an item support on/off capabilities without being part of a set, consider using Modifier.toggleable

This version requires both MutableInteractionSource and Indication to work properly. Use another overload if you don't need these parameters.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

val option1 = Color.Red
val option2 = Color.Blue
var selectedOption by remember { mutableStateOf(option1) }
Column {
    Text("Selected: $selectedOption")
    Row {
        listOf(option1, option2).forEach { color ->
            val selected = selectedOption == color
            Box(
                Modifier
                    .size(100.dp)
                    .background(color = color)
                    .selectable(
                        selected = selected,
                        onClick = { selectedOption = color }
                    )
            )
        }
    }
}
Parameters
boolean selected

whether or not this item is selected in a mutually exclusion set

@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit press events when this selectable is being pressed.

Indication indication

indication to be shown when the modified element is pressed. By default, the indication from LocalIndication will be used. Set to null to show no indication, or current value from LocalIndication to show theme default

boolean enabled

whether or not this selectable will handle input events and appear enabled from a semantics perspective

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

callback to invoke when this item is clicked

SemanticsModifierKt.clearAndSetSemantics

default final @NonNull Modifier SemanticsModifierKt.clearAndSetSemantics(
    @NonNull Modifier receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull SemanticsPropertyReceiverUnit> properties
)

Clears the semantics of all the descendant nodes and sets new semantics.

In the merged semantics tree, this clears the semantic information provided by the node's descendants (but not those of the layout node itself, if any) and sets the provided semantics. (In the unmerged tree, the semantics node is marked with "SemanticsConfiguration.isClearingSemantics", but nothing is actually cleared.)

Compose's default semantics provide baseline usability for screen-readers, but this can be used to provide a more polished screen-reader experience: for example, clearing the semantics of a group of tiny buttons, and setting equivalent actions on the card containing them.

Parameters
@ExtensionFunctionType @NonNull Function1<@NonNull SemanticsPropertyReceiverUnit> properties

properties to add to the semantics. SemanticsPropertyReceiver will be provided in the scope to allow access for common properties and its values.

SemanticsModifierKt.semantics

default final @NonNull Modifier SemanticsModifierKt.semantics(
    @NonNull Modifier receiver,
    boolean mergeDescendants,
    @ExtensionFunctionType @NonNull Function1<@NonNull SemanticsPropertyReceiverUnit> properties
)

Add semantics key/value pairs to the layout node, for use in testing, accessibility, etc.

The provided lambda receiver scope provides "key = value"-style setters for any SemanticsPropertyKey. Additionally, chaining multiple semantics modifiers is also a supported style.

The resulting semantics produce two SemanticsNode trees:

The "unmerged tree" rooted at SemanticsOwner.unmergedRootSemanticsNode has one SemanticsNode per layout node which has any SemanticsModifier on it. This SemanticsNode contains all the properties set in all the SemanticsModifiers on that node.

The "merged tree" rooted at SemanticsOwner.rootSemanticsNode has equal-or-fewer nodes: it simplifies the structure based on mergeDescendants and clearAndSetSemantics. For most purposes (especially accessibility, or the testing of accessibility), the merged semantics tree should be used.

Parameters
boolean mergeDescendants

Whether the semantic information provided by the owning component and its descendants should be treated as one logical entity. Most commonly set on screen-reader-focusable items such as buttons or form fields. In the merged semantics tree, all descendant nodes (except those themselves marked mergeDescendants) will disappear from the tree, and their properties will get merged into the parent's configuration (using a merging algorithm that varies based on the type of property -- for example, text properties will get concatenated, separated by commas). In the unmerged semantics tree, the node is simply marked with SemanticsConfiguration.isMergingSemanticsOfDescendants.

@ExtensionFunctionType @NonNull Function1<@NonNull SemanticsPropertyReceiverUnit> properties

properties to add to the semantics. SemanticsPropertyReceiver will be provided in the scope to allow access for common properties and its values.

ShadowKt.shadow

default final @NonNull Modifier ShadowKt.shadow(
    @NonNull Modifier receiver,
    @NonNull Dp elevation,
    @NonNull Shape shape,
    boolean clip,
    @NonNull Color ambientColor,
    @NonNull Color spotColor
)

Creates a graphicsLayer that draws a shadow. The elevation defines the visual depth of the physical object. The physical object has a shape specified by shape.

If the passed shape is concave the shadow will not be drawn on Android versions less than 10.

Note that elevation is only affecting the shadow size and doesn't change the drawing order. Use a androidx.compose.ui.zIndex modifier if you want to draw the elements with larger elevation after all the elements with a smaller one.

Usage of this API renders this composable into a separate graphics layer

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.unit.dp

Box(
    Modifier.shadow(12.dp, RectangleShape)
        .size(100.dp, 100.dp)
)
Parameters
@NonNull Dp elevation

The elevation for the shadow in pixels

@NonNull Shape shape

Defines a shape of the physical object

boolean clip

When active, the content drawing clips to the shape.

See also
graphicsLayer

Example usage:

SizeKt.defaultMinSize

default final @NonNull Modifier SizeKt.defaultMinSize(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight
)

Constrain the size of the wrapped layout only when it would be otherwise unconstrained: the minWidth and minHeight constraints are only applied when the incoming corresponding constraint is 0. The modifier can be used, for example, to define a default min size of a component, while still allowing it to be overidden with smaller min sizes across usages.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.requiredSizeIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun DefaultMinBox(modifier: Modifier = Modifier) {
    Box(
        modifier.defaultMinSize(minWidth = 100.dp, minHeight = 100.dp)
            .background(Color.Blue)
    )
}
// This will be a 100.dp x 100.dp blue box. Because we are not providing any min constraints
// to the DefaultMinBox, defaultMinSize will apply its min constraints.
DefaultMinBox()
// This will be a 50.dp x 50.dp blue box. Because we are providing min constraints
// to the DefaultMinBox, defaultMinSize will not apply its min constraints.
DefaultMinBox(Modifier.requiredSizeIn(minWidth = 50.dp, minHeight = 50.dp))
// Note that if DefaultMinBox used requiredSizeIn or sizeIn rather than
// defaultMinSize, the min constraints would have been applied with either
// of the above usages.

SizeKt.fillMaxHeight

default final @NonNull Modifier SizeKt.fillMaxHeight(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxHeight of the incoming measurement constraints, by setting the minimum height and the maximum height to be equal to the maximum height multiplied by fraction. Note that, by default, the fraction is 1, so the modifier will make the content fill the whole available height. If the incoming maximum height is Constraints.Infinity this modifier will have no effect.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.fillMaxHeight().background(Color.Red), contentAlignment = Alignment.Center) {
    Box(Modifier.size(100.dp).background(color = Color.Magenta))
}
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.requiredSize(100.dp).background(Color.Red), contentAlignment = Alignment.Center) {
    // The inner Box will be (30.dp x 50.dp).
    Box(
        Modifier.requiredWidth(30.dp)
            .fillMaxHeight(0.5f)
            .background(color = Color.Magenta)
    )
}
Parameters
float fraction

The fraction of the maximum height to use, between 0 and 1, inclusive.

Example usage:

SizeKt.fillMaxSize

default final @NonNull Modifier SizeKt.fillMaxSize(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxWidth and Constraints.maxHeight of the incoming measurement constraints, by setting the minimum width and the maximum width to be equal to the maximum width multiplied by fraction, as well as the minimum height and the maximum height to be equal to the maximum height multiplied by fraction. Note that, by default, the fraction is 1, so the modifier will make the content fill the whole available space. If the incoming maximum width or height is Constraints.Infinity this modifier will have no effect in that dimension.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.fillMaxSize().background(Color.Red), contentAlignment = Alignment.Center) {
    Box(Modifier.size(100.dp).background(color = Color.Magenta))
}
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.requiredSize(100.dp).background(Color.Red), contentAlignment = Alignment.Center) {
    // The inner Box will be (50.dp x 50.dp).
    Box(
        Modifier.requiredWidth(30.dp)
            .fillMaxSize(0.5f)
            .background(color = Color.Magenta)
    )
}
Parameters
float fraction

The fraction of the maximum size to use, between 0 and 1, inclusive.

Example usage:

SizeKt.fillMaxWidth

default final @NonNull Modifier SizeKt.fillMaxWidth(@NonNull Modifier receiver, float fraction)

Have the content fill (possibly only partially) the Constraints.maxWidth of the incoming measurement constraints, by setting the minimum width and the maximum width to be equal to the maximum width multiplied by fraction. Note that, by default, the fraction is 1, so the modifier will make the content fill the whole available width. If the incoming maximum width is Constraints.Infinity this modifier will have no effect.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.fillMaxWidth().background(Color.Red), contentAlignment = Alignment.Center) {
    Box(Modifier.size(100.dp).background(color = Color.Magenta))
}
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box(Modifier.requiredSize(100.dp).background(Color.Red), contentAlignment = Alignment.Center) {
    // The inner Box will be (50.dp x 30.dp).
    Box(
        Modifier.fillMaxWidth(fraction = 0.5f)
            .requiredHeight(30.dp)
            .background(color = Color.Magenta)
    )
}
Parameters
float fraction

The fraction of the maximum width to use, between 0 and 1, inclusive.

Example usage:

SizeKt.height

default final @NonNull Modifier SizeKt.height(@NonNull Modifier receiver, @NonNull Dp height)

Declare the preferred height of the content to be exactly heightdp. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

For a modifier that sets the height of the content regardless of the incoming constraints see Modifier.requiredHeight. See width or size to set other preferred dimensions. See widthIn, heightIn or sizeIn to set a preferred size range.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.height
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box {
    Box(Modifier.height(100.dp).aspectRatio(1f).background(Color.Blue))
}

SizeKt.heightIn

default final @NonNull Modifier SizeKt.heightIn(@NonNull Modifier receiver, @NonNull Dp min, @NonNull Dp max)

Constrain the height of the content to be between mindp and maxdp as permitted by the incoming measurement Constraints. If the incoming constraints are more restrictive the requested size will obey the incoming constraints and attempt to be as close as possible to the preferred size.

SizeKt.requiredHeight

default final @NonNull Modifier SizeKt.requiredHeight(@NonNull Modifier receiver, @NonNull Dp height)

Declare the height of the content to be exactly heightdp. The incoming measurement Constraints will not override this value. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See requiredHeightIn and requiredSizeIn to set a size range. See height to set a preferred height, which is only respected when the incoming constraints allow it.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// The result is a 50.dp x 50.dp blue box centered in a 100.dp x 100.dp space.
// Note that although a previous modifier asked it to be 100.dp height, this
// will not be respected. They would be respected if height was used instead of requiredHeight.
Box(
    Modifier
        .requiredHeight(100.dp)
        .requiredHeight(50.dp)
        .aspectRatio(1f)
        .background(Color.Blue)
)

SizeKt.requiredHeightIn

default final @NonNull Modifier SizeKt.requiredHeightIn(
    @NonNull Modifier receiver,
    @NonNull Dp min,
    @NonNull Dp max
)

Constrain the height of the content to be between mindp and maxdp. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

SizeKt.requiredSize

default final @NonNull Modifier SizeKt.requiredSize(@NonNull Modifier receiver, @NonNull Dp size)

Declare the size of the content to be exactly sizedp width and height. The incoming measurement Constraints will not override this value. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See requiredSizeIn to set a size range. See size to set a preferred size, which is only respected when the incoming constraints allow it.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// The result is a 50.dp x 50.dp red box centered in a 100.dp x 100.dp space.
// Note that although a previous modifier asked it to be 100.dp x 100.dp, this
// will not be respected. They would be respected if size was used instead of requiredSize.
Box(
    Modifier
        .requiredSize(100.dp, 100.dp)
        .requiredSize(50.dp, 50.dp)
        .background(Color.Red)
)

SizeKt.requiredSize

default final @NonNull Modifier SizeKt.requiredSize(@NonNull Modifier receiver, @NonNull DpSize size)

Declare the size of the content to be exactly size. The incoming measurement Constraints will not override this value. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See requiredSizeIn to set a size range. See size to set a preferred size, which is only respected when the incoming constraints allow it.

SizeKt.requiredSize

default final @NonNull Modifier SizeKt.requiredSize(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Dp height
)

Declare the size of the content to be exactly widthdp and heightdp. The incoming measurement Constraints will not override this value. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See requiredSizeIn to set a size range. See size to set a preferred size, which is only respected when the incoming constraints allow it.

SizeKt.requiredSizeIn

default final @NonNull Modifier SizeKt.requiredSizeIn(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight,
    @NonNull Dp maxWidth,
    @NonNull Dp maxHeight
)

Constrain the width of the content to be between minWidthdp and maxWidthdp, and the height of the content to be between minHeightdp and maxHeightdp. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

SizeKt.requiredWidth

default final @NonNull Modifier SizeKt.requiredWidth(@NonNull Modifier receiver, @NonNull Dp width)

Declare the width of the content to be exactly widthdp. The incoming measurement Constraints will not override this value. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

See requiredWidthIn and requiredSizeIn to set a size range. See width to set a preferred width, which is only respected when the incoming constraints allow it.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// The result is a 50.dp x 50.dp magenta box centered in a 100.dp x 100.dp space.
// Note that although a previous modifier asked it to be 100.dp width, this
// will not be respected. They would be respected if width was used instead of requiredWidth.
Box(
    Modifier
        .requiredWidth(100.dp)
        .requiredWidth(50.dp)
        .aspectRatio(1f)
        .background(Color.Magenta)
)

SizeKt.requiredWidthIn

default final @NonNull Modifier SizeKt.requiredWidthIn(
    @NonNull Modifier receiver,
    @NonNull Dp min,
    @NonNull Dp max
)

Constrain the width of the content to be between mindp and maxdp. If the content chooses a size that does not satisfy the incoming Constraints, the parent layout will be reported a size coerced in the Constraints, and the position of the content will be automatically offset to be centered on the space assigned to the child by the parent layout under the assumption that Constraints were respected.

SizeKt.size

default final @NonNull Modifier SizeKt.size(@NonNull Modifier receiver, @NonNull Dp size)

Declare the preferred size of the content to be exactly sizedp square. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

For a modifier that sets the size of the content regardless of the incoming constraints, see Modifier.requiredSize. See width or height to set width or height alone. See widthIn, heightIn or sizeIn to set a preferred size range.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box {
    Box(Modifier.size(100.dp, 100.dp).background(Color.Red))
}

SizeKt.size

default final @NonNull Modifier SizeKt.size(@NonNull Modifier receiver, @NonNull DpSize size)

Declare the preferred size of the content to be exactly size. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

For a modifier that sets the size of the content regardless of the incoming constraints, see Modifier.requiredSize. See width or height to set width or height alone. See widthIn, heightIn or sizeIn to set a preferred size range.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp

Box {
    Box(Modifier.size(DpSize(100.dp, 100.dp)).background(Color.Red))
}

SizeKt.size

default final @NonNull Modifier SizeKt.size(
    @NonNull Modifier receiver,
    @NonNull Dp width,
    @NonNull Dp height
)

Declare the preferred size of the content to be exactly widthdp by heightdp. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

For a modifier that sets the size of the content regardless of the incoming constraints, see Modifier.requiredSize. See width or height to set width or height alone. See widthIn, heightIn or sizeIn to set a preferred size range.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box {
    Box(Modifier.size(100.dp, 100.dp).background(Color.Red))
}

SizeKt.sizeIn

default final @NonNull Modifier SizeKt.sizeIn(
    @NonNull Modifier receiver,
    @NonNull Dp minWidth,
    @NonNull Dp minHeight,
    @NonNull Dp maxWidth,
    @NonNull Dp maxHeight
)

Constrain the width of the content to be between minWidthdp and maxWidthdp and the height of the content to be between minHeightdp and maxHeightdp as permitted by the incoming measurement Constraints. If the incoming constraints are more restrictive the requested size will obey the incoming constraints and attempt to be as close as possible to the preferred size.

SizeKt.width

default final @NonNull Modifier SizeKt.width(@NonNull Modifier receiver, @NonNull Dp width)

Declare the preferred width of the content to be exactly widthdp. The incoming measurement Constraints may override this value, forcing the content to be either smaller or larger.

For a modifier that sets the width of the content regardless of the incoming constraints see Modifier.requiredWidth. See height or size to set other preferred dimensions. See widthIn, heightIn or sizeIn to set a preferred size range.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Box {
    Box(Modifier.width(100.dp).aspectRatio(1f).background(Color.Magenta))
}

SizeKt.widthIn

default final @NonNull Modifier SizeKt.widthIn(@NonNull Modifier receiver, @NonNull Dp min, @NonNull Dp max)

Constrain the width of the content to be between mindp and maxdp as permitted by the incoming measurement Constraints. If the incoming constraints are more restrictive the requested size will obey the incoming constraints and attempt to be as close as possible to the preferred size.

SizeKt.wrapContentHeight

default final @NonNull Modifier SizeKt.wrapContentHeight(
    @NonNull Modifier receiver,
    @NonNull Alignment.Vertical align,
    boolean unbounded
)

Allow the content to measure at its desired height without regard for the incoming measurement minimum height constraint, and, if unbounded is true, also without regard for the incoming measurement maximum height constraint. If the content's measured size is smaller than the minimum height constraint, align it within that minimum height space. If the content's measured size is larger than the maximum height constraint (only possible when unbounded is true), align over the maximum height space.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Here the result will be a 50.dp x 20.dp blue box centered vertically in a 50.dp x 50.dp
// space. Because of the size modifier, if wrapContentHeight did not exist,
// the blue rectangle would actually be 50.dp x 50.dp to satisfy the size set by the modifier.
// However, because we provide wrapContentHeight, the blue rectangle is specified to be wrap
// content in height - if the desired height is smaller than 50.dp, it will be centered
// vertically in this space. Therefore the 50.dp x 20.dp is centered vertically in the space.
Box(
    Modifier.size(50.dp)
        .wrapContentHeight(Alignment.CenterVertically)
        .height(20.dp)
        .background(Color.Blue)
)

SizeKt.wrapContentSize

default final @NonNull Modifier SizeKt.wrapContentSize(
    @NonNull Modifier receiver,
    @NonNull Alignment align,
    boolean unbounded
)

Allow the content to measure at its desired size without regard for the incoming measurement minimum width or minimum height constraints, and, if unbounded is true, also without regard for the incoming maximum constraints. If the content's measured size is smaller than the minimum size constraint, align it within that minimum sized space. If the content's measured size is larger than the maximum size constraint (only possible when unbounded is true), align within the maximum space.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Here the result will be a 20.dp x 20.dp blue box top-centered in a 40.dp x 40.dp space.
// Because of the sizeIn modifier, if wrapContentSize did not exist, the blue rectangle
// would actually be 40.dp x 40.dp to satisfy the min size set by the modifier. However,
// because we provide wrapContentSize, the blue rectangle is specified to be wrap
// content - if the desired size is smaller than 40.dp x 40.dp, it will be top-centered in
// this space. Therefore the 20.dp x 20.dp is top-centered in the space.
Box(
    Modifier.sizeIn(minWidth = 40.dp, minHeight = 40.dp)
        .wrapContentSize(Alignment.TopCenter)
        .size(20.dp)
        .background(Color.Blue)
)

SizeKt.wrapContentWidth

default final @NonNull Modifier SizeKt.wrapContentWidth(
    @NonNull Modifier receiver,
    @NonNull Alignment.Horizontal align,
    boolean unbounded
)

Allow the content to measure at its desired width without regard for the incoming measurement minimum width constraint, and, if unbounded is true, also without regard for the incoming measurement maximum width constraint. If the content's measured size is smaller than the minimum width constraint, align it within that minimum width space. If the content's measured size is larger than the maximum width constraint (only possible when unbounded is true), align over the maximum width space.

Example usage:

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// Here the result will be a 20.dp x 50.dp blue box centered vertically in a 50.dp x 50.dp
// space. Because of the size modifier, if wrapContentWidth did not exist,
// the blue rectangle would actually be 50.dp x 50.dp to satisfy the size set by the modifier.
// However, because we provide wrapContentWidth, the blue rectangle is specified to be wrap
// content in width - if the desired width is smaller than 50.dp, it will be centered
// horizontally in this space. Therefore the 50.dp x 20.dp is centered horizontally
// in the space.
Box(
    Modifier.size(50.dp)
        .wrapContentWidth(Alignment.CenterHorizontally)
        .width(20.dp)
        .background(Color.Blue)
)

SoftwareKeyboardInterceptionModifierKt.onInterceptKeyBeforeSoftKeyboard

@ExperimentalComposeUiApi
default final @NonNull Modifier SoftwareKeyboardInterceptionModifierKt.onInterceptKeyBeforeSoftKeyboard(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onInterceptKeyBeforeSoftKeyboard
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events before they are sent to the software keyboard.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent

// When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
// and then back up to the parent. At any stage you can stop the propagation by returning
// true to indicate that you consumed the event.
Box(
    Modifier
        .onPreviewKeyEvent { keyEvent1 -> false }
        .onKeyEvent { keyEvent4 -> false }
) {
    Box(
        Modifier
            .onPreviewKeyEvent { keyEvent2 -> false }
            .onKeyEvent { keyEvent3 -> false }
            .focusable()
    )
}
Parameters
@NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onInterceptKeyBeforeSoftKeyboard

This callback is invoked when the user interacts with the hardware keyboard. While implementing this callback, return true to stop propagation of this event. If you return false, the key event will be sent to this SoftKeyboardInterceptionModifierNode's parent, and ultimately to the software keyboard.

SoftwareKeyboardInterceptionModifierKt.onPreInterceptKeyBeforeSoftKeyboard

@ExperimentalComposeUiApi
default final @NonNull Modifier SoftwareKeyboardInterceptionModifierKt.onPreInterceptKeyBeforeSoftKeyboard(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onPreInterceptKeyBeforeSoftKeyboard
)

Adding this modifier to the modifier parameter of a component will allow it to intercept hardware key events before they are sent to the software keyboard. This modifier is similar to onInterceptKeyBeforeSoftKeyboard, but allows a parent composable to intercept the hardware key event before any child.

import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.key.onPreviewKeyEvent

// When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
// and then back up to the parent. At any stage you can stop the propagation by returning
// true to indicate that you consumed the event.
Box(
    Modifier
        .onPreviewKeyEvent { keyEvent1 -> false }
        .onKeyEvent { keyEvent4 -> false }
) {
    Box(
        Modifier
            .onPreviewKeyEvent { keyEvent2 -> false }
            .onKeyEvent { keyEvent3 -> false }
            .focusable()
    )
}
Parameters
@NonNull Function1<@NonNull KeyEvent, @NonNull Boolean> onPreInterceptKeyBeforeSoftKeyboard

This callback is invoked when the user interacts with the hardware keyboard. It gives ancestors of a focused component the chance to intercept a KeyEvent. Return true to stop propagation of this event. If you return false, the key event will be sent to this SoftKeyboardInterceptionModifierNode's child. If none of the children consume the event, it will be sent back up to the root KeyInputModifierNode using the onKeyEvent callback, and ultimately to the software keyboard.

SystemGestureExclusionKt.systemGestureExclusion

default final @NonNull Modifier SystemGestureExclusionKt.systemGestureExclusion(
    @NonNull Modifier receiver
)

Excludes the layout rectangle from the system gesture.

SystemGestureExclusionKt.systemGestureExclusion

default final @NonNull Modifier SystemGestureExclusionKt.systemGestureExclusion(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull LayoutCoordinates, @NonNull Rect> exclusion
)

Excludes a rectangle within the local layout coordinates from the system gesture. After layout, exclusion is called to determine the Rect to exclude from the system gesture area.

The LayoutCoordinates of the Modifier's location in the layout is passed as passed as exclusion's parameter.

TestTagKt.testTag

default final @NonNull Modifier TestTagKt.testTag(@NonNull Modifier receiver, @NonNull String tag)

Applies a tag to allow modified element to be found in tests.

This is a convenience method for a semantics that sets SemanticsPropertyReceiver.testTag.

ToggleableKt.toggleable

default final @NonNull Modifier ToggleableKt.toggleable(
    @NonNull Modifier receiver,
    boolean value,
    boolean enabled,
    Role role,
    @NonNull Function1<@NonNull BooleanUnit> onValueChange
)

Configure component to make it toggleable via input and accessibility events

This version has no MutableInteractionSource or Indication parameters, default indication from LocalIndication will be used. To specify MutableInteractionSource or Indication, use another overload.

import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

var checked by remember { mutableStateOf(false) }
// content that you want to make toggleable
Text(
    modifier = Modifier.toggleable(value = checked, onValueChange = { checked = it }),
    text = checked.toString()
)
Parameters
boolean value

whether Toggleable is on or off

boolean enabled

whether or not this toggleable will handle input events and appear enabled for semantics purposes

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function1<@NonNull BooleanUnit> onValueChange

callback to be invoked when toggleable is clicked, therefore the change of the state in requested.

See also
triStateToggleable

if you require support for an indeterminate state.

ToggleableKt.toggleable

default final @NonNull Modifier ToggleableKt.toggleable(
    @NonNull Modifier receiver,
    boolean value,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function1<@NonNull BooleanUnit> onValueChange
)

Configure component to make it toggleable via input and accessibility events.

This version requires both MutableInteractionSource and Indication to work properly. Use another overload if you don't need these parameters.

import androidx.compose.foundation.selection.toggleable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier

var checked by remember { mutableStateOf(false) }
// content that you want to make toggleable
Text(
    modifier = Modifier.toggleable(value = checked, onValueChange = { checked = it }),
    text = checked.toString()
)
Parameters
boolean value

whether Toggleable is on or off

@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit PressInteraction.Press when this toggleable is being pressed.

Indication indication

indication to be shown when modified element is pressed. Be default, indication from LocalIndication will be used. Pass null to show no indication, or current value from LocalIndication to show theme default

boolean enabled

whether or not this toggleable will handle input events and appear enabled for semantics purposes

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function1<@NonNull BooleanUnit> onValueChange

callback to be invoked when toggleable is clicked, therefore the change of the state in requested.

See also
triStateToggleable

if you require support for an indeterminate state.

ToggleableKt.triStateToggleable

default final @NonNull Modifier ToggleableKt.triStateToggleable(
    @NonNull Modifier receiver,
    @NonNull ToggleableState state,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to make it toggleable via input and accessibility events with three states: On, Off and Indeterminate.

TriStateToggleable should be used when there are dependent Toggleables associated to this component and those can have different values.

This version has no MutableInteractionSource or Indication parameters, default indication from LocalIndication will be used. To specify MutableInteractionSource or Indication, use another overload.

import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.selection.triStateToggleable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.state.ToggleableState

var checked by remember { mutableStateOf(ToggleableState.Indeterminate) }
// content that you want to make toggleable
Text(
    modifier = Modifier.triStateToggleable(
        state = checked,
        onClick = {
            checked =
                if (checked == ToggleableState.On) ToggleableState.Off else ToggleableState.On
        }
    ),
    text = checked.toString()
)
Parameters
@NonNull ToggleableState state

current value for the component

boolean enabled

whether or not this triStateToggleable will handle input events and appear enabled for semantics purposes

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

will be called when user clicks the toggleable.

See also
toggleable

if you want to support only two states: on and off

ToggleableKt.triStateToggleable

default final @NonNull Modifier ToggleableKt.triStateToggleable(
    @NonNull Modifier receiver,
    @NonNull ToggleableState state,
    @NonNull MutableInteractionSource interactionSource,
    Indication indication,
    boolean enabled,
    Role role,
    @NonNull Function0<Unit> onClick
)

Configure component to make it toggleable via input and accessibility events with three states: On, Off and Indeterminate.

TriStateToggleable should be used when there are dependent Toggleables associated to this component and those can have different values.

This version requires both MutableInteractionSource and Indication to work properly. Use another overload if you don't need these parameters.

import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.selection.triStateToggleable
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.state.ToggleableState

var checked by remember { mutableStateOf(ToggleableState.Indeterminate) }
// content that you want to make toggleable
Text(
    modifier = Modifier.triStateToggleable(
        state = checked,
        onClick = {
            checked =
                if (checked == ToggleableState.On) ToggleableState.Off else ToggleableState.On
        }
    ),
    text = checked.toString()
)
Parameters
@NonNull ToggleableState state

current value for the component

@NonNull MutableInteractionSource interactionSource

MutableInteractionSource that will be used to emit PressInteraction.Press when this triStateToggleable is being pressed.

Indication indication

indication to be shown when modified element is pressed. Be default, indication from LocalIndication will be used. Pass null to show no indication, or current value from LocalIndication to show theme default

boolean enabled

whether or not this triStateToggleable will handle input events and appear enabled for semantics purposes

Role role

the type of user interface element. Accessibility services might use this to describe the element or do customizations

@NonNull Function0<Unit> onClick

will be called when user clicks the toggleable.

See also
toggleable

if you want to support only two states: on and off

TransformableKt.transformable

default final @NonNull Modifier TransformableKt.transformable(
    @NonNull Modifier receiver,
    @NonNull TransformableState state,
    boolean lockRotationOnZoomPan,
    boolean enabled
)

Enable transformation gestures of the modified UI element.

Users should update their state themselves using default TransformableState and its onTransformation callback or by implementing TransformableState interface manually and reflect their own state in UI when using this component.

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.animateZoomBy
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

Box(
    Modifier
        .size(200.dp)
        .clipToBounds()
        .background(Color.LightGray)
) {
    // set up all transformation states
    var scale by remember { mutableStateOf(1f) }
    var rotation by remember { mutableStateOf(0f) }
    var offset by remember { mutableStateOf(Offset.Zero) }
    val coroutineScope = rememberCoroutineScope()
    // let's create a modifier state to specify how to update our UI state defined above
    val state = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
        // note: scale goes by factor, not an absolute difference, so we need to multiply it
        // for this example, we don't allow downscaling, so cap it to 1f
        scale = max(scale * zoomChange, 1f)
        rotation += rotationChange
        offset += offsetChange
    }
    Box(
        Modifier
            // apply pan offset state as a layout transformation before other modifiers
            .offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }
            // add transformable to listen to multitouch transformation events after offset
            .transformable(state = state)
            // optional for example: add double click to zoom
            .pointerInput(Unit) {
                detectTapGestures(
                    onDoubleTap = {
                        coroutineScope.launch { state.animateZoomBy(4f) }
                    }
                )
            }
            .fillMaxSize()
            .border(1.dp, Color.Green),
        contentAlignment = Alignment.Center
    ) {
        Text(
            "\uD83C\uDF55",
            fontSize = 32.sp,
            // apply other transformations like rotation and zoom on the pizza slice emoji
            modifier = Modifier.graphicsLayer {
                scaleX = scale
                scaleY = scale
                rotationZ = rotation
            }
        )
    }
}
Parameters
@NonNull TransformableState state

TransformableState of the transformable. Defines how transformation events will be interpreted by the user land logic, contains useful information about on-going events and provides animation capabilities.

boolean lockRotationOnZoomPan

If true, rotation is allowed only if touch slop is detected for rotation before pan or zoom motions. If not, pan and zoom gestures will be detected, but rotation gestures will not be. If false, once touch slop is reached, all three gestures are detected.

boolean enabled

whether zooming by gestures is enabled or not

TransformableKt.transformable

@ExperimentalFoundationApi
default final @NonNull Modifier TransformableKt.transformable(
    @NonNull Modifier receiver,
    @NonNull TransformableState state,
    @NonNull Function0<@NonNull Boolean> canPan,
    boolean lockRotationOnZoomPan,
    boolean enabled
)

Enable transformation gestures of the modified UI element.

Users should update their state themselves using default TransformableState and its onTransformation callback or by implementing TransformableState interface manually and reflect their own state in UI when using this component.

This overload of transformable modifier provides canPan parameter, which allows the caller to control when the pan can start. making pan gesture to not to start when the scale is 1f makes transformable modifiers to work well within the scrollable container. See example:

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.animateZoomBy
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.rememberTransformableState
import androidx.compose.foundation.gestures.transformable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Text
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

Row(
    Modifier
        .size(width = 120.dp, height = 100.dp)
        .horizontalScroll(rememberScrollState())
) {
    // first child of the scrollable row is a transformable
    Box(
        Modifier
            .size(100.dp)
            .clipToBounds()
            .background(Color.LightGray)
    ) {
        // set up all transformation states
        var scale by remember { mutableStateOf(1f) }
        var rotation by remember { mutableStateOf(0f) }
        var offset by remember { mutableStateOf(Offset.Zero) }
        val coroutineScope = rememberCoroutineScope()
        // let's create a modifier state to specify how to update our UI state defined above
        val state = rememberTransformableState { zoomChange, offsetChange, rotationChange ->
            // note: scale goes by factor, not an absolute difference, so we need to multiply it
            // for this example, we don't allow downscaling, so cap it to 1f
            scale = max(scale * zoomChange, 1f)
            rotation += rotationChange
            offset += offsetChange
        }
        Box(
            Modifier
                // apply pan offset state as a layout transformation before other modifiers
                .offset { IntOffset(offset.x.roundToInt(), offset.y.roundToInt()) }
                // add transformable to listen to multitouch transformation events after offset
                // To make sure our transformable work well within pager or scrolling lists,
                // disallow panning if we are not zoomed in.
                .transformable(state = state, canPan = { scale != 1f })
                // optional for example: add double click to zoom
                .pointerInput(Unit) {
                    detectTapGestures(
                        onDoubleTap = {
                            coroutineScope.launch { state.animateZoomBy(4f) }
                        }
                    )
                }
                .fillMaxSize()
                .border(1.dp, Color.Green),
            contentAlignment = Alignment.Center
        ) {
            Text(
                "\uD83C\uDF55",
                fontSize = 32.sp,
                // apply other transformations like rotation and zoom on the pizza slice emoji
                modifier = Modifier.graphicsLayer {
                    scaleX = scale
                    scaleY = scale
                    rotationZ = rotation
                }
            )
        }
    }
    // other children are just colored boxes
    Box(
        Modifier
            .size(100.dp)
            .background(Color.Red)
            .border(2.dp, Color.Black)
    )
}
Parameters
@NonNull TransformableState state

TransformableState of the transformable. Defines how transformation events will be interpreted by the user land logic, contains useful information about on-going events and provides animation capabilities.

@NonNull Function0<@NonNull Boolean> canPan

whether the pan gesture can be performed or not

boolean lockRotationOnZoomPan

If true, rotation is allowed only if touch slop is detected for rotation before pan or zoom motions. If not, pan and zoom gestures will be detected, but rotation gestures will not be. If false, once touch slop is reached, all three gestures are detected.

boolean enabled

whether zooming by gestures is enabled or not

WindowInsetsConnectionKt.imeNestedScroll

@ExperimentalLayoutApi
default final @NonNull Modifier WindowInsetsConnectionKt.imeNestedScroll(@NonNull Modifier receiver)

Controls the soft keyboard as a nested scrolling on Android R and later. This allows the user to drag the soft keyboard up and down.

After scrolling, the IME will animate either to the fully shown or fully hidden position, depending on the position and fling.

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.imeNestedScroll
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Text
import androidx.compose.ui.Modifier

LazyColumn(
    modifier = Modifier
        .fillMaxSize() // fill the window
        .imePadding() // pad out the bottom for the IME
        .imeNestedScroll(), // scroll IME at the bottom
    reverseLayout = true // First item is at the bottom
) {
    // content
    items(50) {
        Text("Hello World")
    }
}

WindowInsetsPaddingKt.captionBarPadding

default final @NonNull Modifier WindowInsetsPaddingKt.captionBarPadding(@NonNull Modifier receiver)

Adds padding to accommodate the caption bar insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.captionBar will be consumed for child layouts as well.

For example, if a parent layout uses displayCutoutPadding, the area that the parent layout pads for the status bars will not be padded again by this captionBarPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.captionBarPadding
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.captionBarPadding()) {
                // app content
            }
        }
    }
}

WindowInsetsPaddingKt.consumeWindowInsets

default final @NonNull Modifier WindowInsetsPaddingKt.consumeWindowInsets(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Consume insets that haven't been consumed yet by other insets Modifiers similar to windowInsetsPadding without adding any padding.

This can be useful when content offsets are provided by WindowInsets.asPaddingValues. This should be used further down the hierarchy than the PaddingValues is used so that the values aren't consumed before the padding is added.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.padding(WindowInsets.navigationBars.asPaddingValues())) {
                Box(Modifier.consumeWindowInsets(WindowInsets.navigationBars)) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.consumeWindowInsets

@ExperimentalLayoutApi
default final @NonNull Modifier WindowInsetsPaddingKt.consumeWindowInsets(
    @NonNull Modifier receiver,
    @NonNull PaddingValues paddingValues
)

Consume paddingValues as insets as if the padding was added irrespective of insets. Layouts further down the hierarchy that use windowInsetsPadding, safeContentPadding, and other insets padding Modifiers won't pad for the values that paddingValues provides. This can be useful when content offsets are provided by layout rather than windowInsetsPadding modifiers.

This method consumes all of paddingValues in addition to whatever has been consumed by other windowInsetsPadding modifiers by ancestors. consumeWindowInsets accepting a WindowInsets argument ensures that its insets are consumed and doesn't consume more if they have already been consumed by ancestors.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            with(LocalDensity.current) {
                val paddingValues = PaddingValues(horizontal = 20.dp)
                Box(
                    Modifier
                        .padding(paddingValues)
                        .consumeWindowInsets(paddingValues)
                ) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.consumedWindowInsets

@ExperimentalLayoutApi
default final @NonNull Modifier WindowInsetsPaddingKt.consumedWindowInsets(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

WindowInsetsPaddingKt.consumedWindowInsets

@ExperimentalLayoutApi
default final @NonNull Modifier WindowInsetsPaddingKt.consumedWindowInsets(
    @NonNull Modifier receiver,
    @NonNull PaddingValues paddingValues
)

WindowInsetsPaddingKt.displayCutoutPadding

default final @NonNull Modifier WindowInsetsPaddingKt.displayCutoutPadding(@NonNull Modifier receiver)

Adds padding to accommodate the display cutout.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.displayCutout will be consumed for child layouts as well.

For example, if a parent layout uses statusBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this displayCutoutPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.displayCutoutPadding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .statusBarsPadding()) {
                Box(
                    Modifier
                        .background(Color.Yellow)
                        .displayCutoutPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.imePadding

default final @NonNull Modifier WindowInsetsPaddingKt.imePadding(@NonNull Modifier receiver)

Adds padding to accommodate the ime insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.ime will be consumed for child layouts as well.

For example, if a parent layout uses navigationBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this imePadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .systemBarsPadding()) {
                Box(Modifier.imePadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.mandatorySystemGesturesPadding

default final @NonNull Modifier WindowInsetsPaddingKt.mandatorySystemGesturesPadding(
    @NonNull Modifier receiver
)

Adds padding to accommodate the mandatory system gestures insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.mandatorySystemGestures will be consumed for child layouts as well.

For example, if a parent layout uses navigationBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this mandatorySystemGesturesPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.mandatorySystemGesturesPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .systemBarsPadding()) {
                // The app content won't interfere with the mandatory system gestures area.
                // It will just be white.
                Box(
                    Modifier
                        .background(Color.White)
                        .mandatorySystemGesturesPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.navigationBarsPadding

default final @NonNull Modifier WindowInsetsPaddingKt.navigationBarsPadding(@NonNull Modifier receiver)

Adds padding to accommodate the navigation bars insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.navigationBars will be consumed for child layouts as well.

For example, if a parent layout uses systemBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this navigationBarsPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .statusBarsPadding()) {
                Box(
                    Modifier
                        .background(Color.Green)
                        .navigationBarsPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.onConsumedWindowInsetsChanged

default final @NonNull Modifier WindowInsetsPaddingKt.onConsumedWindowInsetsChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull WindowInsetsUnit> block
)

Calls block with the WindowInsets that have been consumed, either by consumeWindowInsets or one of the padding Modifiers, such as imePadding.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.MutableWindowInsets
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.exclude
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.onConsumedWindowInsetsChanged
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeContent
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            val remainingInsets = remember { MutableWindowInsets() }
            val safeContent = WindowInsets.safeContent
            Box(
                Modifier
                    .navigationBarsPadding()
                    .onConsumedWindowInsetsChanged { consumedWindowInsets ->
                        remainingInsets.insets = safeContent.exclude(consumedWindowInsets)
                    }) {
                // padding can be used without recomposition when insets change.
                val padding = remainingInsets.asPaddingValues()
                Box(Modifier.padding(padding))
            }
        }
    }
}

WindowInsetsPaddingKt.safeContentPadding

default final @NonNull Modifier WindowInsetsPaddingKt.safeContentPadding(@NonNull Modifier receiver)

Adds padding to accommodate the safe content insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.safeContent will be consumed for child layouts as well.

For example, if a parent layout uses navigationBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this safeContentPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.safeContent
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Black)
                    .systemBarsPadding()) {
                // The app content will only be drawn where there is no possible
                // gesture confusion and content will not be drawn over.
                // The rest will be plain white
                Box(
                    Modifier
                        .background(Color.White)
                        .safeContentPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.safeDrawingPadding

default final @NonNull Modifier WindowInsetsPaddingKt.safeDrawingPadding(@NonNull Modifier receiver)

Adds padding to accommodate the safe drawing insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.safeDrawing will be consumed for child layouts as well.

For example, if a parent layout uses statusBarsPadding, the area that the parent pads for the status bars will not be padded again by this safeDrawingPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Black)
                    .systemBarsPadding()) {
                // The app content won't have anything drawing over it, but all the
                // background not in the status bars will be white.
                Box(
                    Modifier
                        .background(Color.White)
                        .safeDrawingPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.safeGesturesPadding

default final @NonNull Modifier WindowInsetsPaddingKt.safeGesturesPadding(@NonNull Modifier receiver)

Adds padding to accommodate the safe gestures insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.safeGestures will be consumed for child layouts as well.

For example, if a parent layout uses navigationBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this safeGesturesPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.safeGesturesPadding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Black)
                    .systemBarsPadding()) {
                // The app content will only be drawn where there is no possible
                // gesture confusion. The rest will be plain white
                Box(
                    Modifier
                        .background(Color.White)
                        .safeGesturesPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.statusBarsPadding

default final @NonNull Modifier WindowInsetsPaddingKt.statusBarsPadding(@NonNull Modifier receiver)

Adds padding to accommodate the status bars insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.statusBars will be consumed for child layouts as well.

For example, if a parent layout uses displayCutoutPadding, the area that the parent layout pads for the status bars will not be padded again by this statusBarsPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .statusBarsPadding()) {
                Box(
                    Modifier
                        .background(Color.Green)
                        .navigationBarsPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.systemBarsPadding

default final @NonNull Modifier WindowInsetsPaddingKt.systemBarsPadding(@NonNull Modifier receiver)

Adds padding to accommodate the system bars insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.systemBars will be consumed for child layouts as well.

For example, if a parent layout uses statusBarsPadding, the area that the parent layout pads for the status bars will not be padded again by this systemBarsPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.ui.Modifier
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.systemBarsPadding()) {
                // app content
            }
        }
    }
}

WindowInsetsPaddingKt.systemGesturesPadding

default final @NonNull Modifier WindowInsetsPaddingKt.systemGesturesPadding(@NonNull Modifier receiver)

Adds padding to accommodate the system gestures insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.systemGestures will be consumed for child layouts as well.

For example, if a parent layout uses waterfallPadding, the area that the parent layout pads for the status bars will not be padded again by this systemGesturesPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.systemGesturesPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .systemBarsPadding()) {
                // The app content won't interfere with the system gestures area.
                // It will just be white.
                Box(
                    Modifier
                        .background(Color.White)
                        .systemGesturesPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.waterfallPadding

default final @NonNull Modifier WindowInsetsPaddingKt.waterfallPadding(@NonNull Modifier receiver)

Adds padding to accommodate the waterfall insets.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from the padding. WindowInsets.Companion.waterfall will be consumed for child layouts as well.

For example, if a parent layout uses systemGesturesPadding, the area that the parent layout pads for the status bars will not be padded again by this waterfallPadding modifier.

When used, the WindowInsets will be consumed.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.waterfallPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(
                Modifier
                    .background(Color.Blue)
                    .systemBarsPadding()) {
                // The app content shouldn't spill over the edges. They will be green.
                Box(
                    Modifier
                        .background(Color.Green)
                        .waterfallPadding()) {
                    // app content
                }
            }
        }
    }
}

WindowInsetsPaddingKt.windowInsetsPadding

default final @NonNull Modifier WindowInsetsPaddingKt.windowInsetsPadding(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Adds padding so that the content doesn't enter insets space.

Any insets consumed by other insets padding modifiers or consumeWindowInsets on a parent layout will be excluded from insets. insets will be consumed for child layouts as well.

For example, if an ancestor uses statusBarsPadding and this modifier uses WindowInsets.Companion.systemBars, the portion of the system bars that the status bars uses will not be padded again by this modifier.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            val insets = WindowInsets.systemBars.union(WindowInsets.ime)
            Box(
                Modifier
                    .background(Color.White)
                    .fillMaxSize()
                    .windowInsetsPadding(insets)) {
                // app content
            }
        }
    }
}
See also
WindowInsets

WindowInsetsPaddingKt.withConsumedWindowInsets

@ExperimentalLayoutApi
default final @NonNull Modifier WindowInsetsPaddingKt.withConsumedWindowInsets(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull WindowInsetsUnit> block
)

WindowInsetsSizeKt.windowInsetsBottomHeight

default final @NonNull Modifier WindowInsetsSizeKt.windowInsetsBottomHeight(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Sets the height to that of insets at the bottom of the screen.

When used, the android.view.WindowInsets will respect the consumed insets from windowInsetsPadding and consumeWindowInsets, but won't consume any insets.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.fillMaxSize()) {
                // Background for navigation bar at the bottom
                Box(Modifier.windowInsetsTopHeight(WindowInsets.navigationBars)
                    .fillMaxWidth()
                    .align(Alignment.BottomCenter)
                    .background(Color.Red)
                )
                // app content
            }
        }
    }
}

WindowInsetsSizeKt.windowInsetsEndWidth

default final @NonNull Modifier WindowInsetsSizeKt.windowInsetsEndWidth(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Sets the width to that of insets at the end of the screen, using either left or right, depending on the LayoutDirection.

When used, the android.view.WindowInsets will respect the consumed insets from windowInsetsPadding and consumeWindowInsets, but won't consume any insets.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.windowInsetsEndWidth
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.fillMaxSize()) {
                // Background for navigation bar at the end
                Box(Modifier.windowInsetsEndWidth(WindowInsets.navigationBars)
                    .fillMaxHeight()
                    .align(Alignment.CenterEnd)
                    .background(Color.Red)
                )
                // app content
            }
        }
    }
}

WindowInsetsSizeKt.windowInsetsStartWidth

default final @NonNull Modifier WindowInsetsSizeKt.windowInsetsStartWidth(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Sets the width to that of insets at the start of the screen, using either left or right, depending on the LayoutDirection.

When used, the android.view.WindowInsets will respect the consumed insets from windowInsetsPadding and consumeWindowInsets, but won't consume any insets.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.windowInsetsStartWidth
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.fillMaxSize()) {
                // Background for navigation bar at the start
                Box(Modifier.windowInsetsStartWidth(WindowInsets.navigationBars)
                    .fillMaxHeight()
                    .align(Alignment.CenterStart)
                    .background(Color.Red)
                )
                // app content
            }
        }
    }
}

WindowInsetsSizeKt.windowInsetsTopHeight

default final @NonNull Modifier WindowInsetsSizeKt.windowInsetsTopHeight(
    @NonNull Modifier receiver,
    @NonNull WindowInsets insets
)

Sets the height to that of insets at the top of the screen.

When used, the android.view.WindowInsets will respect the consumed insets from windowInsetsPadding and consumeWindowInsets, but won't consume any insets.

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsTopHeight
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.core.view.WindowCompat

class SampleActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        super.onCreate(savedInstanceState)
        setContent {
            Box(Modifier.fillMaxSize()) {
                // Background for status bar at the top
                Box(Modifier.windowInsetsTopHeight(WindowInsets.statusBars)
                    .fillMaxWidth()
                    .align(Alignment.TopCenter)
                    .background(Color.Red)
                )
                // app content
            }
        }
    }
}

ZIndexModifierKt.zIndex

default final @NonNull Modifier ZIndexModifierKt.zIndex(@NonNull Modifier receiver, float zIndex)

Creates a modifier that controls the drawing order for the children of the same layout parent. A child with larger zIndex will be drawn on top of all the children with smaller zIndex. When children have the same zIndex the original order in which the parent placed the children is used.

Note that if there would be multiple zIndex modifiers applied for the same layout the sum of their values will be used as the final zIndex. If no zIndex were applied for the layout then the default zIndex is 0.

import androidx.compose.foundation.layout.Box
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.zIndex

Box {
    Text("Drawn second", Modifier.zIndex(1f))
    Text("Drawn first")
}