跪拜 Guibai
← Back to the summary

Jetpack Compose 1.13.0 Deprecates Form Input APIs, Stabilizes List Prefetch and Exit Snapshots

Jetpack Compose 1.13.0 was released, and Material 3 updated to 1.5.0 at the same time. The upgrade uses BOM 2026.11.01, requires Kotlin 2.2 or higher, and compileSdk 37.1.

Upgrade configuration

Update the BOM in the Compose module's build.gradle.kts. The .1 in 37.1 is configured with minorApiLevel; writing only compileSdk = 37 will select the major version 37. When upgrading these libraries, targetSdk and minSdk still adjust according to the app's own plan.

android {
    compileSdk {
        version = release(37) {
            minorApiLevel = 1
        }
    }
}

dependencies {
    val composeBom = platform("androidx.compose:compose-bom:2026.11.01")
    implementation(composeBom)
    androidTestImplementation(composeBom)
    implementation("androidx.compose.ui:ui")
    implementation("androidx.compose.foundation:foundation")
    implementation("androidx.compose.animation:animation")
    implementation("androidx.compose.material3:material3")
}

If a custom container relies on onFocusedBoundsChanged to scroll to the current input field, after upgrading use onFocusChanged to listen for focus, then call BringIntoViewRequester. If you really need the focus rectangle, you can call FocusTargetModifierNode.getFocusedRect() on demand in a custom Modifier.Node. LazyColumn and verticalScroll already have their own focus scrolling.

There is also a fix for pages that mix View and Compose. When Compose is placed inside a View container like NestedScrollView or CoordinatorLayout, a fast fling may stop abruptly because of a miscalculated velocity handover. After upgrading, quickly scroll the original page past the intersection to check this behavior.

Input field migration

Foundation's BasicTextField(value, onValueChange) and VisualTransformation are deprecated, and Compose Material 2 is also in a deprecated state. Material 3 1.5.0's value-driven TextField and OutlinedTextField overloads are still available; new forms can directly use the overloads that take TextFieldState. The stateless overloads of Slider and RangeSlider are deprecated; migrate to SliderState and RangeSliderState respectively.

Using a 16-digit card number displayed in groups of four as an example, InputTransformation intercepts overly long input, and OutputTransformation only inserts spaces in the UI. When submitting the form, read the original value from state.text. Compose handles cursor position mapping after inserting separators.

import androidx.compose.foundation.text.input.InputTransformation
import androidx.compose.foundation.text.input.maxLengthReject
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

@Composable
fun CardNumberField() {
    val state = rememberTextFieldState()
    OutlinedTextField(
        state = state,
        label = { Text("卡号") },
        inputTransformation = InputTransformation.maxLengthReject(16),
        outputTransformation = {
            // Insert spaces from right to left; the left group's index is unaffected.
            for (offset in 12 downTo 4 step 4) {
                if (length > offset) insert(offset, " ")
            }
        },
    )
}

图片

The old maxLength() is also deprecated in 1.13. Suppose the field already has 12 characters and you paste 5 more; maxLengthReject(16) will reject the entire paste. If you want to keep the 4 characters that fit, use maxLengthTrim(16). Forms that only allow digits should also add character validation; the length limit rule only handles length.

There is also a small change in text display. When multiple languages or mixed font sizes cause adjacent lines to squeeze together, LineHeightStyle.Mode.PerLine can calculate line height based on each line's content. If a tall glyph in one line needs more space, other lines can maintain their own line heights.

In Material 3 1.5.0, BasicAlertDialog and several TopAppBar variants also become stable APIs. If a custom design system only needs Material 3's ripple and focus effects, you can depend on androidx.compose.material3:material3-ripple separately. This library supports embedded focus rings; when you Tab to a button with the keyboard, you can see the focus position.

List prefetch

LazyLayoutCacheWindow becomes a stable API. Previously you passed the window to rememberLazyListState or rememberLazyGridState; now you pass it directly to LazyColumn, LazyVerticalGrid, etc. Lazy waterfall lists can also be configured; the front and back of the window follow the scroll direction.

For example, if the list viewport is 600.dp and the front window is set to 0.4f, that means prefetching roughly 240.dp in the scroll direction. The back window at 0.15f means keeping roughly 90.dp of content that just left the screen, reusable when scrolling back. The distance is based on the viewport; when item heights vary, the number of items the window can hold changes.

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

@Composable
fun MessageList(messages: List<String>) {
    val state = rememberLazyListState()
    LazyColumn(
        state = state,
        cacheWindow = LazyLayoutCacheWindow(
            aheadFraction = 0.4f,
            behindFraction = 0.15f,
        ),
    ) {
        items(messages) { message -> Text(message) }
    }
}

图片

These two ratios are just examples. Compose 1.13's default strategy adjusts the front window based on visible item sizes, ranging from 10% to 50% of the viewport, with a default back window of 0. When creating a window manually, the default also fills the front window in non-scrolling scenarios like initial layout and data updates. For image lists that expand the window, compare dropped frames and memory on fast scroll and reverse scroll with the same data set before deciding to override defaults.

For regular layouts, there are stable FlexBox and Grid. When a tab bar needs to wrap based on available width, use FlexBox; after enabling wrapping, use maxItemsInEachLine to limit the number of items per line. When you need to explicitly arrange two-dimensional rows and columns, use Grid. This time, ConstraintLayout and MotionLayout from constraintlayout-compose are deprecated; the XML View version of ConstraintLayout can continue to be used with its original dependency.

Exit animation

When closing a detail card, if selectedTitle is immediately set to null, the old AnimatedVisibility still keeps the content composed until the animation ends. If the content uses selectedTitle?.let { ... }, the card text may disappear first, leaving only an empty shell during exit.

CapturedAnimatedVisibility releases the child composition immediately when hidden and draws a snapshot of the last frame during the exit phase. The page can immediately clear the selected item, and the text before closing is still visible during fade-out.

import androidx.compose.animation.CapturedAnimatedVisibility
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun SelectionDetails(selectedTitle: String?) {
    CapturedAnimatedVisibility(
        visible = selectedTitle != null,
        exit = fadeOut(),
    ) {
        selectedTitle?.let { title ->
            Card { Text(title, Modifier.padding(16.dp)) }
        }
    }
}

图片

If you need to refresh a countdown during exit, or if a child needs Modifier.animateEnterExit(), continue using AnimatedVisibility and keep the state needed for exit until the animation ends.

Progressive blur

When creating a header image, you can keep the upper half's details and only blur the bottom transition. The following BlurStop sets the blur radius to 0 for the first 55%, then gradually increases to 18.dp for the remaining area. Apply this Modifier to the image, and lay the title as another child of the Box on top, so the text stays clear.

import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.blur.BlurRadiusSpec
import androidx.compose.ui.graphics.blur.BlurStop
import androidx.compose.ui.unit.dp

val headerBlur = Modifier.blur {
    blurRadiusSpec = BlurRadiusSpec.verticalGradient(
        stops = listOf(
            BlurStop(fraction = 0f, radius = 0.dp),
            BlurStop(fraction = 0.55f, radius = 0.dp),
            BlurStop(fraction = 1f, radius = 18.dp),
        ),
    )
}

图片

Progressive blur requires Android 13 (API 33) and above; uniform-radius blur has been supported since Android 12 (API 31). On older systems, unsupported effects are drawn as sharp content. If the title needs extra contrast against the header's bottom, add a separate semi-transparent gradient behind the text.

For star-shaped avatars or polygon buttons, Foundation's new PolygonShape can be passed directly to Modifier.clip; the shape adjusts to the layout size. To animate between two shapes, use MorphPolygonShape; the animation progress can be read during drawing.

Performance and testing

When scroll position changes frequently, if you only use it to decide whether to show a "back to top" button, you can write remember(listState) { computedStateOf { listState.firstVisibleItemIndex > 0 } }. Reading this state recomputes; for composition, a boolean value change is what causes recomposition from this read. When the calculation has overhead like sorting a collection, derivedStateOf can still cache results. The computation block of computedStateOf should only read state.

Perfetto's recomposition tracing now records state reads and writes and call stacks, useful for finding which write causes repeated recomposition. Recording this information adds overhead; turn off recomposition tracing when measuring frame time.

UI tests can now use ComposeUiTestConfig's TestFailurePolicy to save screenshots and semantic trees on failure. When onNodeWithText() fails to find a node, first check the screenshot for the text. If the text is on the screen but the semantic node is merged by the parent, use useUnmergedTree = true to check against child nodes.

Finally

What version of Compose have you upgraded to?

#Android #JetpackCompose #Kotlin

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

無表情

Just upgraded to 1.13, cachewindow is a bit like RecyclerView.