Google is committed to advancing racial equity for Black communities. See how.

Compose Material

Build Jetpack Compose UIs with ready to use Material Design Components. This is the higher level entry point of Compose, designed to provide components that match those described at www.material.io.
Latest Update Current Stable Release Next Release Candidate Beta Release Alpha Release
October 14, 2020 - - - 1.0.0-alpha05

Structure

Compose is combination of 7 Maven Group Ids within androidx. Each Group contains a targeted subset of functionality, each with it's own set of release notes.

This table explains the groups and links to each set of release notes.

GroupDescription
compose.animationBuild animations in their Jetpack Compose applications to enrich the user experience.
compose.compilerTransform @Composable functions and enable optimizations with a Kotlin compiler plugin.
compose.foundationWrite Jetpack Compose applications with ready to use building blocks and extend foundation to build your own design system pieces.
compose.materialBuild Jetpack Compose UIs with ready to use Material Design Components. This is the higher level entry point of Compose, designed to provide components that match those described at www.material.io.
compose.runtimeFundamental building blocks of Compose's programming model and state management, and core runtime for the Compose Compiler Plugin to target.
compose.uiFundamental components of compose UI needed to interact with the device, including layout, drawing, and input.
uiWorks with the Jetpack Compose library.

Declaring dependencies

To add a dependency on Compose, you must add the Google Maven repository to your project. Read Google's Maven repository for more information.

Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

dependencies {
    implementation "androidx.compose.material:material:1.0.0-alpha05"
}

android {
    buildFeatures {
        compose true
    }

    composeOptions {
        kotlinCompilerVersion "1.4.0"
        kotlinCompilerExtensionVersion "1.0.0-alpha05"
    }
}

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
    kotlinOptions {
        jvmTarget = "1.8"
        freeCompilerArgs += ["-Xallow-jvm-ir-dependencies", "-Xskip-prerelease-check"]
    }
}

For more information about dependencies, see Add build dependencies.

Feedback

Your feedback helps make Jetpack better. Let us know if you discover new issues or have ideas for improving this library. Please take a look at the existing issues in this library before you create a new one. You can add your vote to an existing issue by clicking the star button.

Create a new issue

See the Issue Tracker documentation for more information.

Version 1.0.0

Version 1.0.0-alpha05

October 14, 2020

androidx.compose.material:material:1.0.0-alpha05, androidx.compose.material:material-icons-core:1.0.0-alpha05, and androidx.compose.material:material-icons-extended:1.0.0-alpha05 are released. Version 1.0.0-alpha05 contains these commits.

API Changes

  • Popups and dialogs now inherit FLAG_SECURE from parent Window. Also added option to configure this explicitly (I64966, b/143778148, b/143778149)
  • Modifier.swipeable has 56.dp thresholds for states by default now (Iab825, b/168610267)
  • all scaffold states marked as @Stable. drawerGesturesEnabled in ScaffoldState moved to Scaffold itself. (I36645, b/168297016)
  • Removes nullable type from Scaffold lambda parameters, you can use emptyContent() to represent no content for a given parameter. (I2b318, b/157633857, b/158551084)
  • Deprecates contentColor() and currentTextStyle() APIs, and replaces them with AmbientContentColor and AmbientTextStyle ambients respectively. You can access the current value by using .current on the ambient property, as with any other ambient. This was change was made for consistency and to avoid having multiple ways to accomplish the same thing. Additionally renames some ambient properties to better describe their purpose as follows:

    • ContentColorAmbient -> AmbientContentColor
    • TextStyleAmbient -> AmbientTextStyle
    • IndicationAmbient -> AmbientIndication
    • EmphasisAmbient -> AmbientEmphasisLevels
    • RippleThemeAmbient -> AmbientRippleTheme (I37b6d)
  • Adds AmbientElevationOverlay, allowing customizing / disabling the default elevation overlay applied to Surfaces in dark theme. (I5b74d)

Bug Fixes

  • As part of the standardization of sentinel values for inline classes, rename Color.Unset to Color.Unspecified for consistency with other inline classes (I97611, b/169797763)
  • TextOverflow.None is introduced. When overflow is None, Text won't handle overflow anymore, and it will report its actual size to LayoutNode. (I175c9, b/158830170)
  • launchInComposition renamed to LaunchedTask to match Compose API guidelines (I99a8e)
  • OnPositionedModifier is renamed to OnGloballyPositionedModifier and onPositioned() is renamed to onGloballyPositioned(). (I587e8, b/169083903)

Version 1.0.0-alpha04

October 1, 2020

androidx.compose.material:material:1.0.0-alpha04, androidx.compose.material:material-icons-core:1.0.0-alpha04, and androidx.compose.material:material-icons-extended:1.0.0-alpha04 are released. Version 1.0.0-alpha04 contains these commits.

API Changes

  • Exposes InteractionState parameters in stateful Material components, to allow hoisting the state and reading / controlling the state. (Iaca5f, b/168025711, b/167164434)
  • Changes the *color parameters on RadioButton and TriStateCheckbox to allow fully customizing the colors used in each state, as well as changing how the colors animate between states if desired. See the new animateDefault* color functions in CheckboxConstants and RadioButtonConstants for more information. (I1c532)
  • Renamed rememberBackdropState to rememberBackdropScaffoldState and added an additional param for the animation clock. Renamed the param backdropScaffoldState of BackdropScaffold to just scaffoldState. Renamed BackdropConstants to BackdropScaffoldConstants. (Ib644d)
  • Added experimental BottomSheetScaffold component. (Ie02f0, b/148996320)
  • Added experimental ModalBottomSheetLayout component. (Ic209e, b/148996320)
  • Renames ButtonConstants/FloatingActionButtonConstants.defaultAnimatedElevation to defaultElevation, and now returns a Dp value instead of an AnimatedValue. (I5f3ed)

Bug Fixes

  • Updated many Graphics APIs
    • Updated scale and rotation transformation APIs to consume a single Offset parameter to represent the pivot coordinate instead of separate float parameters for the x/y coordinates in DrawScope and DrawTransform
    • Removed Rect.expandToInclude and Rect.join methods
    • Updated Radius documentation to say oval in addition to elliptical
    • Added documentation to indicate the public constructor for the inline Radius class is not to be called directly but instead Radius objects should be instantiated through their function constructors
    • Removed RoundRect APIs to query topRight, bottomRight, bottomCenter, etc.
    • Deprecated Rect.shift in favor of Rect.translate
    • Removed RoundRect.grow and Rect.shrink APIs
    • Renamed RoundRect.outerRect to Rect.boundingRect
    • Removed RoundRect.middleRect/tallMiddleRect/wideMiddleRect and Rect.isStadium methods
    • Renamed RoundRect.longestSide to RoundRect.maxDimension
    • Renamed RoundRect.shortestSide to RoundRect.minDimension
    • Changed RoundRect.center to be a property instead of a function
    • Updated RoundRect constructor to consume Radius properties instead of individual parameters for x/y radius values
    • Removed Size APIs that assumed it was a Rectangle with origin at 0,0
    • Added a destructing API to Radius
    • Migrated various RoundRect extension functions to be properties instead
    • (I8f5c7, b/168762961)
  • foundation.Box was deprecated. Please use foundation.layout.Box instead. (Ie5950, b/167680279)
  • Stack was renamed to Box. The previously existing Box will be deprecated in favor of the new Box in compose.foundation.layout. The behavior of the new Box is to stack children one on top of another when it has multiple children - this is different from the previous Box, which was behaving similar to a Column. (I94893, b/167680279)
  • Box decoration parameters have been deprecated. If you want to have decorations/padding on your box, use Modifiers instead (Modifier.background, Modifier.border, Modifier.padding) (Ibae92, b/167680279)
  • Updated many Graphics APIs
    • Updated DrawScope APIs with scoped transformation methods to indicate that the transformation is only applied within the callback and removed after the callback is invoked
    • Updated clipPath documentation to refer to Path instead of rounded rectangle
    • Fixed spacing in documentation for right parameter in clipPath
    • Renamed DrawScope.drawCanvas to drawIntoCanvas and removed size parameter
    • Renamed dx/dy parameters in inset method to horizontal and vertical
    • Added inset overload that provides the same inset value to all 4 bounds
    • Removed documentation on inset method indicating that inset would be applied to all 4 sides
    • Updated documentation for Rect class
    • Updated comments on Rect parameters to match kdoc style
    • Removed Rect.join and Rect.expandToInclude
    • Created overload for Rect.translate(offset) and deprecated Rect.shift
    • (If086a, b/167737376)
  • We prevented static imports of contents of layout scopes (e.g. alignWithSiblings in RowScope). The explicit scope alternative should be used instead: with(RowScope) { Modifier.alignWithSiblings(FirstBaseline) }. (I216be, b/166760797)

Version 1.0.0-alpha03

September 16, 2020

androidx.compose.material:material:1.0.0-alpha03, androidx.compose.material:material-icons-core:1.0.0-alpha03, and androidx.compose.material:material-icons-extended:1.0.0-alpha03 are released. Version 1.0.0-alpha03 contains these commits.

API Changes

  • RenamesBottomNavigationItem's onSelect parameter to onClick (I91925, b/161809324)
  • Adds InteractionState parameter to BottomNavigationItem and Tab, allowing hoisting this state and adjusting how the component appears in different states. (Ia3e9e, b/168025711)
  • Removes disabledBackgroundColor and disabledContentColor parameters from buttons. You should instead use the new default color functions inside ButtonConstants. If you are already setting contentColor / backgroundColor explicitly, you should instead use these default functions and customize some / all of the parameters to avoid overwriting the color for both enabled / disabled states. (If9b52)
  • Textfield's background color does not implicitly apply transparency alpha anymore. Instead, any color provided through the backgroundColor parameter will be applied directly. (Iecee9, b/167951441)
  • InnerPadding was renamed to PaddingValues. (I195f1, b/167389171)
  • The params resistanceFactorAtMin and resistanceFactorAtMax in Modifier.swipeable were replaced with a single resistance param. A new defaultResistanceConfig method was added in SwipeableConstants. (I54238)
  • Adds animated stateful elevation support for Button and FloatingActionButton. The elevation now animates between default and pressed states. To customize the elevation between states, please use ButtonConstants.defaultAnimatedElevation() and FloatingActionButtonConstants.defaultAnimatedElevation() instead of setting a flat Dp value in all cases. (I37925)
  • Label became an optional parameter inside TextField and OutlinedTextField (I267f6, b/162234081)

Bug Fixes

  • Global testing functions such as onNode or waitForIdle are now deprecated, please migrate to their new counterparts that are defined on ComposeTestRule (I7f45a)
  • DpConstraints and APIs using it were deprecated. (I90cdb, b/167389835)
  • The parameters minWidth and maxWidth of widthIn were renamed to min and max. Similarly for preferredWidthIn, heightIn, preferredHeightIn. (I0e5e1, b/167389544)
  • Remove scroll forward/backward semantics actions. Added steps in AccessibilityRangeInfo. (Ia47b0)
  • Usages of gravity were consistently renamed to align or alignment in layout APIs. (I2421a, b/164077038)
  • Added onNode and other global methods on ComposeTestRule as the current global ones are going to be deprecated. (Ieae36)
  • Moved createAndroidComposeRule and AndroidInputDispatcher from androidx.ui.test.android to androidx.ui.test (Idef08, b/164060572)

Version 1.0.0-alpha02

September 2, 2020

androidx.compose.material:material:1.0.0-alpha02, androidx.compose.material:material-icons-core:1.0.0-alpha02, and androidx.compose.material:material-icons-extended:1.0.0-alpha02 are released. Version 1.0.0-alpha02 contains these commits.

API Changes

  • Added an experimental BackdropScaffold component. (Iad908)

Bug Fixes

  • Matrix4 was replaced with Matrix. All other parts of vectormath package have been removed. (Ibd665, b/160140398)

Version 1.0.0-alpha01

August 26, 2020

androidx.compose.material:material:1.0.0-alpha01, androidx.compose.material:material-icons-core:1.0.0-alpha01, and androidx.compose.material:material-icons-extended:1.0.0-alpha01 are released. Version 1.0.0-alpha01 contains these commits.

Known Issue

= The first character in a material TextField cannot be removed using a backspace (b/165956313)

Version 0.1.0-dev

Version 0.1.0-dev17

August 19, 2020

androidx.compose.material:material:0.1.0-dev17, androidx.compose.material:material-icons-core:0.1.0-dev17, and androidx.compose.material:material-icons-extended:0.1.0-dev17 are released. Version 0.1.0-dev17 contains these commits.

API Changes

  • Previously deprecated RadioGroup and RadioGroupItems have been removed. Use Row and RadioBotton instead (I381b7, b/163806637)
  • Removed onFocusChanged callbacks from TextField. Use Modifier.focusObserver instead. (I51089, b/161297615)
  • Modifier.drawBorder has been deprecated. Use Modifier.border instead. Border data class has been replaced by BorderStroke (I4257d, b/158160576)
  • Renamed some properties in SwipeableState: swipeTarget -> targetValue, swipeProgress -> progress, swipeDirection -> direction. Added a rememberSwipeableState function for creating SwipeableStates. (I2fc9c, b/163129614, b/163132293)
  • Snackbar support with positioning and proper queueing has been added. Access it via SnackbarHostState.showSnackbar suspend function. Additionally:
    • SnackbarHost components has been added. It hosts Snackbars based on the state and is responsible for transition between snackbars.
    • SnackbarHostState has been added to allow for control over snackbars, snackbars hosts and to decouple it from the ScaffoldState. you can access this state via scaffoldState.snackbarHostState as well.
    • Snackbar overload has been added to support common interface between snackbarHostState and snackbars itself. (I79aaa)
  • Adds enabled parameter to IconButton, and reorders parameters in IconToggleButton (I0a941, b/161809385, b/161807956)
  • ListItem version with String-based API has been removed. Use slot version instead. (Ib8f57, b/161804681)
  • Removed deprecated FilledTextField component. Please use TextField instead to get the Material Design implementation of the Filled text field. (I5e889)
  • AlertDialog now uses FlowRow for buttons (I00ec1, b/161809319, b/143682374)
  • Added params in Modifier.swipeable for changing the amount of resistance when swiping past the bounds. Removed [min/max]Value params. (I93d98)
  • Added backgroundColor parameter to LinearProgressIndicator and removed internal padding from CircularProgressIndicator. Added new ProgressIndicatorConstants.DefaultProgressAnimationSpec which can be used as the default AnimationSpec when animating progress between values (If38b5, b/161809914, b/161804677)
  • Optional param velocityThreshold added to Modifier.swipeable. (I698ba)
  • bottomBarSize, fabSize and others and not available anymore in ScaffoldState. Use Modifier.onPosition instead on the component you'd like to know the size of. contentColor and Modifier pamateres have been added to Scaffold (Ic6f7b, b/161811485, b/157174382)
  • Renames and reorders some parameters in Tab for consistency with other APIs (Ia2d12, b/161807532)
  • Splits TabRow into TabRow and ScrollableTabRow, removing isScrollable from TabRow. Also exposes edgePadding in ScrollableTabRow, which allows controlling the free space before / after the tabs. (I583e8, b/161809544)
  • The TabRow object has been removed, replacing it with TabConstants. TabRow.TabPosition has moved to be top level (TabPosition), and indicatorContainer has been renamed to indicator. See the samples and documentation for detailed information on how to use the updated API, and defaults. (I54d45, b/161809544)
  • The thresholds param in Modifier.swipeable was tweaked; it now takes a pair of states (of type T) and returns the threshold between them in the form of a ThresholdConfig. A param dismissThresholds was added to SwipeToDismiss, which is a lambda (DismissDirection) -> ThresholdConfig. (Ie1080)
  • Slider has more colors for granular customization (I73e64, b/161810475)
  • Card's color param was renamed to backgroundColor (I01fc1, b/161809546)
  • Snackbar has customizable background and content colors now (I238f2, b/161804381)
  • modifier, backgroundColor, contentColor and scrimColor customization params has been added to Drawers (I23655, b/161804378)
  • The state { ... } composable is now deprecated in favor of explicit calls to remember { mutableStateOf(...) } for clarity. This reduces the overall API surface and number of concepts for state management, and matches the by mutableStateOf() pattern for class property delegation. (Ia5727)
  • Button's padding param was renamed to contentPadding (Id252e, b/161809394)
  • Add an experimental material component SwipeToDismiss. (I129e5)

Bug Fixes

  • Removed onChildPositioned and OnChildPositionedModifier. Developers should use onPositioned and OnPositionedModifier on the child layout instead. (I4522e, b/162109766)
  • Added mergePolicy lambda to SemanticsPropertyKey. This can be used to define a custom policy for mergeAllDescendants semantics merging. The default policy is to use the parent value if already present, otherwise the child value. (Iaf6c4, b/161979921)
  • IntSize is now an inline class (I2bf42)
  • PlacementScope.placeAbsolute() was renamed to PlacementScope.place(), and the previous PlacementScope.place() was renamed to PlacementScope.placeRelative(). As a result, the PlacementScope.place() method will not automatically mirror the position in right-to-left contexts anymore. If this is desired, use PlacementScope.placeRelative() instead. (I873ac, b/162916675)
  • Deprecated PxBounds in favor of Rect. Updated all usages of PxBounds with rect and added proper deprecate/replace with annotations to assist with the migration. (I37038, b/162627058)
  • Renamed RRect to RoundRect to better fit compose naming patterns Created similar function constructors to RRect and deprecated RRect function constructors (I5d325)

Version 0.1.0-dev16

August 5, 2020

androidx.compose.material:material:0.1.0-dev16, androidx.compose.material:material-icons-core:0.1.0-dev16, and androidx.compose.material:material-icons-extended:0.1.0-dev16 are released. Version 0.1.0-dev16 contains these commits.

API Changes

  • Colors is now a final class instead of an interface. Instead of extending and providing a custom implementation, you should create a new ambient for your custom theme object, and access the theme object through the new ambient in your components, similar to how MaterialTheme works internally. (Ibae84)
  • Renamed ColorPalette to Colors, to better map to the Material color system and remove confusion over ColorPalette being a 'generic' theming object, as opposed to being a specific implementation of the Material color system. Additionally renames lightColorPalette and darkColorPalette to lightColors and darkColors respectively. (I9e976, b/161812111)
  • Renames BottomNavigationItem's text parameter to label, onSelected to onSelect, activeColor to selectedContentColor, inactiveColor to unselectedContentColor and updates parameter ordering to match guidelines. (Icb605, b/161809324)
  • Modifier.stateDraggable was completely reworked and renamed to Modifier.swipeable. A new SwipeableState class was introduced, and DrawerState and BottomDrawerState were refactored to inherit from it. [Modal/Bottom]DrawerLayout no longer takes an onStateChange parameter. (I72332, b/148023068)
  • foundation.shape.corner package were flatten to foundation.share (I46491, b/161887429)
  • Added ExperimentalMaterialApi annotation. RippleTheme marked as Experimental (Ic5fa0, b/161784800)
  • Material FilledTextField was renamed to TextField and foundational TextField was renamed to BaseTextField to make simplest desired API easy to discover and use (Ia6242, b/155482676)

Bug Fixes

  • OnChildPositioned has been deprecated. Use OnPositioned on the child instead. (I87f95, b/162109766)
  • Address broad API fixes (I077bc)
    1. Remove unused OffsetBase interface
    2. Align Offset and IntOffset classes to have a consistent API surface
    3. Rename IntOffset.Origin to IntOffset.Zero to be consistent with Offset API
    4. Moved nativeCanvas method off of Canvas interface to support consumers to create their own Canvas instances
    5. Created stub EmptyCanvas class to refactor DrawScope to be a non-null parameter instead of lateinit and ensure non-nullability of the field
    6. Renamed ClipOp enums to be Pascal Case
    7. Renamed FilterQuality enums to be Pascal Case
    8. Renamed StrokeJoin enums to be Pascal Case
    9. Renamed PointMode enums to be Pascal Case
    10. Renamed PaintingStyle enums to be Pascal Case
    11. Renamed PathFillType enums to be Pascal Case
    12. Renamed StrokeCap enums to be Pascal Case
    13. Updated DrawCache implementation to no longer use lateinit params
    14. Updated DrawScope to no longer use lazy delegation for fillPaint and strokePaint internal parameters
    15. Updated Image composable to avoid Box usage for less overhead
    16. Updated Outline class to have @Immutable annotations
    17. Updated PathNode to have @Immutable annotations for each path instruction
    18. Updated Vector subcomposition to remove redundant conditional checks for equality as compose already handles them
    19. Deprecated Rect companion constructor methods in favor of function constructors
    20. Updated Brush classes and function constructors with @Immutable and @Stable APIs
    21. Updated VertexMode enum to be PascalCase
    22. Updated DrawScope selectPaint method to conditionally overwrite stroke parameters on the paint if they have changed
    23. Updated Size to add destructuring API, rename UnspecifiedSize to Unspecified and removed unused methods
  • Move dialog to ui (I47fa6)
  • Removed SemanticsNodeInteraction.performPartialGesture. Use SemanticsNodeInteraction.performGesture instead. (Id9b62)
  • Renamed SemanticsNodeInteraction.getBoundsInRoot() to SemanticsNodeInteraction.getUnclippedBoundsInRoot() (Icafdf, b/161336532)
  • The APIs for right-to-left support has been updated. LayoutDirectionAmbient has been added, which can be used to read and change the layout direction. Modifier.rtl and Modifier.ltr have been removed. (I080b3)
  • Modifier.deternimateProgress has been renamed to Modifier.progressSemantics (I9c0b4)
  • Updates material-icons-extended with the latest icons added to Material.io/icons (I4b1d3)
  • Require type T to be explicitly specified for transitionDefinition. (I1aded)
  • Modifier.plus has been deprecated, use Modifier.then instead. 'Then' has a stronger signal of ordering, while also prohibits to type Modifier.padding().background() + anotherModifier, which breaks the chain and harder to read (Iedd58, b/161529964)
  • Renamed AndroidComposeTestRule to createAndroidComposeRule. (I70aaf)
  • Add isFocused() and isNotFocused() SemanticsMatcher. (I0b760)
  • Removed BaseGestureScope.globalBounds, which shouldn't be used from tests. Use coordinates local to the node with which you're interacting instead. (Ie9b08)
  • Fixed popup position on cut-out displays. (Idd7dd)
  • Modifier.drawBackground has been renamed to Modifier.background (I13677)

Version 0.1.0-dev15

July 22, 2020

androidx.compose.material:material:0.1.0-dev15, androidx.compose.material:material-icons-core:0.1.0-dev15, and androidx.compose.material:material-icons-extended:0.1.0-dev15 are released. Version 0.1.0-dev15 contains these commits.

Dependencies Update

  • To use the 0.1.0-dev15 version of Compose, you will need to update your dependencies according to the new code snippets shown above in Declaring dependencies.

API Changes

  • @Model annotation is now deprecated. Use state and mutableStateOf as alternatives. This deprecation decision was reached after much careful discussion.

    Justification

    Rationale includes but is not limited to:

    • Reduces API surface area and concepts we need to teach
    • More closely aligns with other comparable toolkits (Swift UI, React, Flutter)
    • Reversible decision. We can always bring @Model back later.
    • Removes corner-case usage and difficult to answer questions about configuring @Model as things we need to handle
    • @Model data classes, equals, hashcode, etc.
    • How do I have some properties “observed” and others not?
    • How do I specify structural vs. referential equality to be used in observation?
    • Reduces “magic” in the system. Would reduce the likelihood of someone assuming system was smarter than it is (ie, it knowing how to diff a list)
    • Makes the granularity of observation more intuitive.
    • Improves refactorability from variable -> property on class
    • Potentially opens up possibilities to do hand-crafted State-specific optimizations
    • More closely aligns with the rest of the ecosystem and reduces ambiguity towards immutable or us “embracing mutable state”

    Migration Notes

    Almost all existing usages of @Model are fairly trivially transformed in one of two ways. The example below has a @Model class with two properties just for the sake of example, and has it being used in a composable.

    @Model class Position(
     var x: Int,
     var y: Int
    )
    
    @Composable fun Example() {
     var p = remember { Position(0, 0) }
     PositionChanger(
       position=p,
       onXChange={ p.x = it }
       onYChange={ p.y = it }
     )
    }
    

    Alternative 1: Use State<OriginalClass> and create copies.

    This approach is made easier with Kotlin’s data classes. Essentially, make all previously var properties into val properties of a data class, and then use state instead of remember, and assign the state value to cloned copies of the original using the data class copy(...) convenience method.

    It’s important to note that this approach only works when the only mutations to that class were done in the same scope that the State instance is created. If the class is internally mutating itself outside of the scope of usage, and you are relying on the observation of that, then the next approach is the one you will want to use.

    data class Position(
     val x: Int,
     val y: Int
    )
    
    @Composable fun Example() {
     var p by state { Position(0, 0) }
     PositionChanger(
       position=p,
       onXChange={ p = p.copy(x=it) }
       onYChange={ p = p.copy(y=it) }
     )
    }
    

    Alternative 2: Use mutableStateOf and property delegates

    This approach is made easier with Kotlin’s property delegates and the mutableStateOf API which allows you to create MutableState instances outside of composition. Essentially, replace all var properties of the original class with var properties with mutableStateOf as their property delegate. This has the advantage that the usage of the class will not change at all, only the internal implementation of it. The behavior is not completely identical to the original example though, as each property is now observed/subscribed to individually, so the recompositions you see after this refactor could be more narrow (a good thing).

    class Position(x: Int, y: Int) {
     var x by mutableStateOf(x)
     var y by mutableStateOf(y)
    }
    
    // source of Example is identical to original
    @Composable fun Example() {
     var p = remember { Position(0, 0) }
     PositionChanger(
       position=p,
       onXChange={ p.x = it }
       onYChange={ p.y = it }
     )
    }
    

    (I409e8, b/152050010, b/146362815, b/146342522, b/143413369, b/135715219, b/143263925, b/139653744)

  • onFocusChange callback in text fields renamed to onFocusChanged (Ida4a1)

  • Added thresholds param in stateDraggable to specify thresholds between anchors. This was used to set a 56dp threshold in bottom drawer. Also BottomDrawerLayout now uses a separate BottomDrawerState enum. (I533fa)

  • Removes previously deprecated Modifier.ripple. Clickable now uses ripple as the default indication (if you have a MaterialTheme {} set in your application) so in most cases you can just use clickable and get ripple indication for free. If you need to customize the color / size / bounded parameter for the ripple, you can manually create a RippleIndication and pass it to clickable as the indication parameter. (I663b2, b/155375067)

  • Removed deprecated override of FilledTextField composable (I7f8f8)

  • Rename Button object (containing the defaults used by Button function) to ButtonConstants (I7c5f7, b/159687878)

  • Button's content slot now behaves as Row (useful when you need to have an icon with a text, see samples on Button how to write it) (I0ff10, b/158677863)

  • RadioGroup and RadioGroupItem have been deprecated. Use Box with Modifier.selectable, Row and Column to make proper set of radioButton choices by your design (I7f5cf, b/149528535)

  • Added Material Outlined Textfield (I1a518)

  • androidx.ui.foundation.TextFieldValue and androidx.ui.input.EditorValue is deprecated. TextField, FilledTextField and CoreTextField composables that uses that type is also deprecated. Please use androidx.ui.input.TextFieldValue instead (I4066d, b/155211005)

  • TabRow.TabPosition not contains position in Dp, not in IntPx (I34a07, b/158577776)

  • Replaced usage of IntPx with Int. Replaced IntPxPosition with IntOffset. Replaced IntPxSize with IntSize. (Ib7b44)

  • In order to consolidate the number of classes used to represent sizing information, standardize on usage of the Size class instead of PxSize. This provides the benefits of an inline class to leverage a long to pack 2 float values to represent width and height represented as floats. (Ic0191)

  • Deprecates Modifier.ripple. Clickable now uses ripple as the default indication (if you have a MaterialTheme {} set in your application) so in most cases you can just use clickable and get ripple indication for free. If you need to customize the color / size / bounded parameter for the ripple, you can manually create a RippleIndication and pass it to clickable as the indication parameter. (I101cd, b/155375067)

  • Scaffold API has been reworked: few parameters changed their name, added new parameters for better customization. Added getter to query sizes of Fab, TopBar and BottomBar (I0e7ce)

  • Added the DropdownMenu component in ui-material, a Material Design menu implementation. (I9bb3d)

  • Allow to show/hide software keyboard manually using SoftwareKeyboardController (Ifb9d6, b/155427736)

  • Modifier.indication has been added to foundation package. Use it to show press/drag/other indication on your custom interactable elements (I8425f, b/155287131)

  • Consolidated CanvasScope implementations so there is now just DrawScope and ContentDrawScope Renamed CanvasScope to DrawScope. Updated DrawScope to implement Density interface and provide LayoutDirection Deleted DrawScope subclass in ContentDrawScope Painter and PainterModifier have been updated to no longer maintain an RTL property themselves as DrawScope provides this already without manually providing it (I1798e)

  • Renames Emphasis.emphasize() to Emphasis.applyEmphasis() (Iceebe)

  • Disabled buttons now visually follows the Material Design specification (I47dcb, b/155076924)

  • FilledTextField gets ime action, visual transformation and keyboard type support (I1f9cf, b/155075201)

  • Adds strokeWidth parameter to CircularProgressIndicator to customize the stroke size. To change the stroke size (height) of a LinearProgressIndicator, you can use Modifier.preferredHeight() or another size modifier. (Icea16, b/154919081)

  • Adds strokeWidth parameter to CircularProgressIndicator to customize the stroke size. To change the stroke size (height) of a LinearProgressIndicator, you can use Modifier.preferredHeight() or another size modifier. (Icea16, b/154919081)

  • Added slot API for trailing and leading icons in the FilledTextField and handling of the error state (Ic12e0)

  • FAB's and Extended FAB's default color has been changed to MaterialTheme.colors.secondary. (I3b9b9, b/154118816)

  • Replaced all nullable Color uses in API with non-nullable and use Color.Unset instead of null (Iabaa7)

  • Renamed EdgeInsets to InnerPadding. Renamed innerPadding parameter of Material Buttons to paddding. (I66165)

  • Slider is now stateless. Users will need to pass and update state by themselves, just like in any other control. (Ia00aa)

  • StaticDrawer was removed. If you need it, use Box with material-spec'ed width instead (I244a7)

  • Added Material Design implementation of Filled Text Field (Ic75cd)

  • Added modifier param to ListItem and reordered params to promote trailing lambda body (I66e21)

  • Adds defaultFontFamily constructor parameter to Typography, allowing specifying the default font family that will be used for any provided TextStyles that do not have a family set. (I89d07)

  • Temporarily removed Material Data Tables from the API surface. (Iaea61)

  • Renamed paramaters in Divider composable (Ic4373)

  • children (Ia6d19)

  • Removes MaterialTheme.emphasisLevels, instead use EmphasisAmbient.current to retrieve the emphasis levels (Ib5e40)

  • Shape theming system is updated according to the Material design specification. Now you can provide small, medium and large shapes to be used by most of the components (Ifb4d1)

  • Changed MaterialTheme APIs such as MaterialTheme.colors(), MaterialTheme.typography() to be properties instead of functions. Remove parentheses from existing calls, no behavioral change is expected. (I3565a)

  • Refactored FloatingActionButton APIs to accept composable lambdas instead of primitives. See updated samples for usage information. (I00622)

  • add enabled param to Checkbox, Switch and Toggleable (I41c16)

  • Ripple is now a Modifier. While Clickable is not yet converted the recommended usage is Clickable(onClick = { ... }, modifier = ripple()) (Ie5200, b/151331852, b/150060763)

  • Surface and Card were moved from androidx.ui.material.surface to androidx.ui.material (I88a6d, b/150863888)

  • Button, FloatingActionButton and Clickable now have a separate enabled param. Some of the params on Button were renamed or reordered. (I54b5a)

  • Renamed Image to ImageAsset to better differentiate the difference between the Image data and the upcoming Image composable used to participate in layout and draw content. _Body:Created extension method on android.graphics.Bitmap, Bitmap.asImageAsset(), to create an instance of an ImageAsset useful for combining traditional Android application development with the compose framework (Id5bbd)

  • Removed Snackbar API with String parameters in favour of using the overload that accepts composable lambdas. See updated samples for usage information (I55f80)

  • Refactored Tab APIs to accept text and icon lambdas, (Ia057e)

  • Added BottomNavigation component, see the docs and samples for usage information (I731a0)

  • Added Icon, IconButton and IconToggleButton, removing AppBarIcon. You can directly replace existing usages of AppBarIcon with IconButton, and they will now have the correct touch target. See the samples for usage information, and see Icons for the provided Material Icons you can use directly with these components. (I96849)

  • Replaced ButtonStyle with distinct functions and removed text (string) overload. See updated samples for usage information. (If63ab, b/146478620, b/146482131)

  • rename Border modifier to DrawBorder (I8ffcc)

  • LayoutCoordinates no longer has a position property. The position property does not make sense when considering LayoutModifiers, rotation, or scaling. Instead, developers should use parentCoordinates and childToLocal() to calculate the transform from one LayoutCoordinate to another.

    LayoutCoordinates uses IntPxSize for the size property instead of PxSize. Layouts use integer pixel sizes for layouts, so all layout sizes should use integers and not floating point values. (I9367b)

  • Breaking changes to the ambients API. See log and Ambient<T> documentation for details (I4c7ee, b/143769776)

  • Scaffold material component has been added. Scaffold implements (I7731b)

  • Replaced DrawBorder in favor of Border Modifier (Id335a)

Bug Fixes

  • FocusModifier is deprecated in favor of Modifier.focus, Modifier.focusRequester, Modifier.focusObserver. FocusState and FocusDetailedState are deprecated in favor of FocusState2 (I46919, b/160822875, b/160922136)
  • VerticalScroller and HoriziontalScroller have been deprecated. Use ScrollableColumn and ScrollableRow for build-in experience with Column/Row behaviour and parameters, or Modifier.verticalScroll and Modifier.horizontalScroll on your own element. Similarly, ScrollerPosition has been deprecated in favor of ScrollState' (I400ce, b/157225838, b/149460415, b/154105299)
  • Modifier.draggable and Modifier.scrollable APIs were reworked. DragDirection was removed in favor of Orientation. State required for scrollable has beed simplified. ScrollableState has been renamed to ScrollableController (Iab63c, b/149460415)
  • runOnIdleCompose renamed to runOnIdle (I83607)
  • Single-value semantics properties now use a calling style. For example, 'semantics { hidden = true }' is now written as: 'semantics { hidden() }'. (Ic1afd, b/145951226, b/145955412)
  • Several testing APIs were renamed to be more intuitive. All findXYZ APIs were renamed to onNodeXYZ. All doXYZ APIs were renamed to performXYZ. (I7f164)
  • Transition API has been changed to return a TransitionState instead of passing the TransitionState to children. This makes the API more consistent with animate() APIs. (I24e38)
  • An IntBounds unit class has been added, representing integer pixel bounds from layout. The API of PopupPositionProvider has been updated to use it. (I0d8d0, b/159596546)
  • A new optional flag useUnmergedTree was added to test finders. (I2ce48)
  • Removed obsolete size testing APIs. (Iba0a0)
  • Removed Shader inline class that wrapped the NativeShader expect class Renamed NativeShader to Shader. The wrapped Shader inline class did not add anything valuable to the API surface and was an inline class, so use the NativeShader class directly. (I25e4d)
  • Popups, Dialogs and Menus are now inheriting the contextual MaterialTheme (Ia3665, b/156527485)
  • Material DropdownMenu are now scrollable. (Ide699)
  • Removed layout direction parameter from the measure block of the Layout() function. Layout direction is however available inside the callback through the measure scope object (Ic7d9d)
  • Use AnimationSpec instead of AnimationBuilder in the top level APIs to clarify the concept of static animation specification -Improve the transition DSL by removing the lambda requirement for creating AnimationSpecs such as tween, spring. They instead take constructor params directly. -Improve the overall ease of use of AnimationSpec opening up constructors instead of relying on builders -Change the duration and delay for KeyFrames and Tween to Int. This eliminates unnecessary type casts and method overloading (for supporting both Long and Int). (Ica0b4)
  • Switch now appears in a disabled state when enabled is set to false (If4624, b/155941869, b/159331694)
  • Modifier.tag was renamed to Modifier.layoutId, to avoid confusion with Modifier.testTag. (I995f0)
  • Alignment line Int positions returned from Placeable#get(AlignmentLine) are now non-null. If the queried alignment line is missing, AlignmentLine.Unspecified will be returned. (I896c5, b/158134875)
  • Refactored Radius class to be an inline class. Removed companion creation methods in favor of function constructor with default parameter to have the radius along the y-axis match that of the mandatory x-axis radius parameter.

    Updated DrawScope.drawRoundRect to consume a single Radius parameter instead of 2 separate float values for the radius along the x and y axis (I46d1b)

  • In order to consolidate the number of classes used to represent positioning information, standardize on usage of the Offset class instead of PxPosition. This provides the benefits of an inline class to leverage a long to pack 2 float values to represent x and y offsets represented as floats. (I3ad98)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters. Deleted Px class in its entirety (I3ff33)

  • Toggleable component has been deprecated. Use Modifier.toggleable instead (I35220, b/157642842)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters (I086f4)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters (Id3434)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters (I97a5a)

  • Fixed onClick not being invoked for DropdonMenuItems. (I3998b, b/157673259)

  • MutuallyExclusiveSetItem has been deprecated. Use Modifier.selectable instead. (I02b47, b/157642842)

  • TestTag is now deprecated. Use Modifier.testTag instead. (If5110, b/157173105)

  • TextField's cursor has a blinking animation (Id10a7)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters (I19d02)

  • VerticalScroller now provides Column out of the box. HorizontalScroller now provides Row out of the box. (Ieca5d, b/157020670)

  • Replaced usage of Px class in various compose classes as part of the large refactoring effort to only rely on Dp and primitive types for pixel parameters (Iede0b)

  • Modifier.semantics has been undeprecated to allow usages for high level components. (I4cfdc)

  • DrawLayer modifiers api has been changed: outlineShape renamed to shape and has the RectangleShape default value and now non-nullable; clipToOutline renamed to clip; clipToBounds removed as it is the same as clip == true with RectangleShape (I7ef11, b/155075735)

  • Updated higher level compose APIs that expose a Canvas to expose CanvasScope instead. This removes the need for consumers to maintain their own Paint objects. For consumers that still require access to a Canvas they can use the drawCanvas extension method which provides a callback to issue drawing commands with the underlying Canvas. (I80afd)

  • AlignmentLineOffset composable is deprecated, please use relativePaddingFrom() modifier instead. CenterAlignmentLine composable is removed. (I60107)

  • WithConstraints trailing lambda API has been changed. Now instead of two params it has a receiver scope which in addition to constraints and layoutDirection provides minWidth, maxWidth, minHeight and maxHeight properties in Dp (I91b9a, b/149979702)

  • Added defaultMinSizeConstraints layout modifier, which sets size constraints to the wrapped layout only when the incoming corresponding constraints are unspecified (0 for min constraints and infinity for max constraints). (I311ea, b/150460257)

  • FocusManagerAmbient is removed. Use FocusModifier.requestFocus to obtain focus. (Ic4826)

  • Created CanvasScope API that wraps a Canvas object to expose a stateless, declarative drawing API surface. Transformations are contained within their own receiver scope and sizing information is also scoped to corresponding inset bounds. It does not require a consumer to maintain its own Paint state object for configuring drawing operations.

    Added CanvasScopeSample as well as updated the demo app to include a declarative graphics demo (Ifd86d)

  • Add cursor color customisation to the TextField (I6e33f)

  • TextFieldValue used with TextField can now be survive activity recreation when used like this: var text by savedInstanceState(saver = TextFieldValue.Saver) { TextFieldValue() } (I5c3ce, b/155075724)

  • Renamed LayoutModifier2 to LayoutModifier. (Id29f3)

  • Removed deprecated LayoutModifier interface. (I2a9d6)

  • Replaced CoreTextField/TextField focusIdentifier parameter with FocusNode in order to integrate with focus subsystem. (I7ea48)

  • Intrinsic measurements functions in Layout and LayoutModifier2 have an IntrinsicMeasureScope receiver now which provides intrinsics query API with implicitly propagated layout direction. (Id9945)

  • New Modifier.zIndex() is added to control the drawing order of the children within the same parent layout. elevation property on DrawLayerModifier is renamed to shadowElevation and doesn't control the drawing order anymore. The params order fo DrawShadow is changed: elevation is now the first one and the shape is the second one with a RectangleShape default. (I20150, b/152417501)

  • RectangleShape moved from androidx.ui.foundation.shape.* to androidx.ui.graphics.* (Ia74d5, b/154507984)

  • TextField API update - merged onFocus and onBlur callbacks into a single onFocusChange(Boolean) callback with parameter (I66cd3)

  • Added verticalGravity and horizontalGravity parameters to Row and Column, respectively. (I7dc5a)

  • Updated wrapContentWidth and wrapContentHeight to expect vertical or horizontal Alignment rather than any Alignment. The gravity modifier was updated to accept vertical or horizontal Alignment. Row, Column and Stack were updated to support custom continuous Alignments. (Ib0728)

  • Created PixelMap API to support querying pixel information from an ImageAsset. (I69ad6)

  • Removes ProvideContentColor, instead just use ContentColorAmbient directly with Providers (Iee942)

  • ui-text-compose module is renamed as ui-text. ui-text now contains CoreText and CoreTextField composables (Ib7d47)

  • ui-text module is renamed as ui-text-core (I57dec)

  • Moved ui-framework/CoreText, CoreTextField composables under ui-text-compose. You might want to include ui-text-compose in your project. (I32042)

  • Improve DrawModifier API:

    • Made the receiver scope for draw() ContentDrawScope
    • Removed all parameters on draw()
    • DrawScope has same interface as former CanvasScope
    • ContentDrawScope has drawContent() method (Ibaced, b/152919067)
  • runOnIdleCompose and runOnUiThread are now global functions instead of methods on ComposeTestRule. (Icbe8f)

  • [Mutable]State property delegate operators moved to extensions to support Kotlin 1.4 property delegate optimizations. Callers must add imports to continue using by state { ... } or by mutableStateOf(...). (I5312c)

  • Added positionInParent and boundsInParent for LayoutCoordinates. (Icacdd, b/152735784)

  • ColoredRect has been deprecated. Use Box(Modifier.preferredSize(width, height).drawBackground(color)) instead. (I499fa, b/152753731)

  • Renamed LayoutResult to MeasureResult. (Id8c68)

  • Added LayoutModifier2, a new API for defining layout modifiers; deprecated LayoutModifier (If32ac)

  • Replaced Modifier plus operator with factory extension functions (I225e4)

  • Draggable has been moved to modifier (Id9b16, b/151959544)

  • ParentData composable is deprecated. You should either create a modifier which implements ParentDataModifier interface, or use LayoutTag modifier if you simply need to tag layout children to recognize them inside the measure block. (I51368, b/150953183)

  • Deprecated Center composable. It should be replaced either with the LayoutSize.Fill + LayoutAlign.Center modifier, or with one of the Box or Stack composables with suitable modifiers applied (Idf5e0)

  • Added VectorPainter API to replace existing subcomposition API for vector graphics. Result of subcomposition is a VectorPainter object instead of a DrawModifier. Deprecated previous DrawVector composables in favor of VectorPainter.

    Renamed Image(Painter) API to PaintBox(Painter) Created Vector composable that behaves like the Image composable except with a VectorAsset instead of an ImageAsset (I9af9a, b/149030271)

  • Renamed LayoutFlexible to LayoutWeight. Renamed tight parameter to fill. (If4738)

  • Removed RepaintBoundary in favor of DrawLayerModifier (I00aa4)

  • DrawVector has been changed from a regular composable function to returning a Modifier drawVector() that will draw the vector as a background to a layout. (I7b8e0)

  • The Opacity composable function has been replaced with the drawOpacity modifier. (I5fb62)

  • Replace composable function Clip with modifier drawClip(). DrawClipToBounds is a convenient modifier to use when you only need to clip to the layer bounds with a rectangle shape. (If28eb)

  • Replaced DrawShadow composable function with drawShadow() modifier. Shadows are now drawn as part of LayerModifier. (I0317a)

  • Added LayerModifier, a modifier that allows adding a RenderNode for a Layout. It allows setting clipping, opacity, rotation, scaling, and shadows. This will replace RepaintBoundary. (I7100d, b/150774014)

  • androidx.compose.ViewComposer has been moved to androidx.ui.node.UiComposer androidx.compose.Emittable has been removed. It was redundant with ComponentNode. androidx.compose.ViewAdapters has been removed. They are no longer a supported use case. Compose.composeInto has been deprecated. Use setContent or setViewContent instead. Compose.disposeComposition has been deprecated. Use the dispose method on the Composition returned by setContent instead. androidx.compose.Compose.subcomposeInto has moved to androidx.ui.core.subcomposeInto ComponentNode#emitInsertAt has been renamed to ComponentNode#insertAt ComponentNode#emitRemoveAt has been renamed to ComponentNode#removeAt ComponentNode#emitMode has been renamed to ComponentNode#move (Idef00)

  • Created Image composable to handle sizing/layout in addition to drawing a given ImageAsset to the screen. This composable also supports drawing any arbitrary Painter instance respecting its intrinsic size as well as supporting a given fixed size or minimum size (Ibcc8f)

  • Deprecated Wrap composable. It can be replaced either with the LayoutAlign modifier or with the Stack composable (Ib237f)

  • WithConstraints got LayoutDirection parameter (I6d6f7)

  • Made the layout direction be propagated from parent layout node to children. Added layout direction modifier. (I3d955)

  • Deprecated: Draw composable is a common source of bugs as it's (I78392, b/149827027)

  • Stack component supports right-to-left directionality (Ic9e00)

  • DrawShape composable was removed. Use DrawBackground modifier instead. (I7ceb2)

  • Support right-to-left direction in LayoutPadding modifier (I9e8da)

  • Added AdapterList, a scrolling list component that only composes and lays out the visible items. Currently known issues include that it is vertical-only and does not fully handle all cases of changes to its children. (Ib351b)

  • Updated the ComposeFlags.COMPOSER_PARAM flag to be true, which will change the code generation strategy for the compose plugin. At a high level, this causes @Composable functions to be generated with an additional synthetic parameter, which is passed through to subsequent @Composable calls in order for the runtime to properly manage execution. This is a significant binary breaking change, however, should preserve source-level compatibility in all sanctioned usage of compose. (I7971c)

  • Added Canvas component. This composable takes up some size (provided by user) and allows you to draw using CanvasScope (I0d622)

  • Density and DensityScope were merged into one interface. Instead of ambientDensity() you can now use DensityAmbient.current. Instead of withDensity(density) just with(density) (I11cb1)

  • Changed LayoutCoordinates to make providedAlignmentLines a Set instead of a Map and have LayoutCoordinates implement the get() operator instead for retrieving a value. This makes it easier for modifiers to modify one or more value of the set without creating a new collection for each modifier. (I0245a)

  • Scrollers now exhibit native Android fling motion behavior. (I922af, b/147493715)

  • Improvements to the API surface of Constraints (I0fd15)