Styles

android/skills/jetpack-compose/theming/styles

作者 android42dc2270e960Complete terms in LICENSE.txt7.7K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫13 天前更新

Use this skill to integrate the Jetpack Compose Styles API into an Android project. This skill guides you through upgrading dependencies, setting up component themes, making custom components styleable, and migrating existing layout properties to use unified styles. Migrate custom design system components, replace hard coded parameters with Style attributes, and use Modifier.styleable for interaction states.

AI 產生的概覽

引導將 Android Jetpack Compose 自訂元件與主題遷移至實驗性 Styles API。

功能
此技能引導代理在 Android 專案中採用 Jetpack Compose Styles API:升級相依套件、開啟實驗性編譯器選項、在 ComponentStyles 檔案中定義元件樣式,並將自訂 composable 從零散的樣式參數改為 Style 參數搭配 Modifier.styleable。它也說明如何把樣式接入自訂主題,並透過螢幕截圖測試與 Compose 預覽驗證遷移結果。產出的是遷移指引與程式碼變更,而非獨立成品檔案。
適用情境
適用於已使用 Jetpack Compose 的 Android 專案,想把自訂設計系統元件或自訂主題遷移至 Styles API 的情境。不適用於 Material Design 元件樣式,也不適用於尚未導入 Compose 相依套件的專案。
執行需求
需要 Android 專案使用 compileSdk 37 或更高版本,並相依於 androidx.compose.foundation:foundation 1.12.0-alpha01 或更高版本(或 Compose BOM 2026.04.01 或更高版本),同時在 build.gradle.kts 中選擇啟用 ExperimentalFoundationStyleApi。視覺驗證可選用模擬器或螢幕截圖測試框架。不含指令碼,僅為說明文件與參考文件。

Limitations

  • Warn the user that this skill is EXPERIMENTAL and requires updating to alpha version of Compose and opting in to the Experimental APIs.
  • This skill only supports custom UI components and custom themes.
  • This skill does not support Material Design component Styles.

Prerequisites

1. Upgrade dependencies

  • The project must use compileSdk version 37 or higher.
  • The project must use androidx.compose.foundation:foundation version 1.12.0-alpha01 or higher.
  • Alternatively, the project must use Compose BOM version 2026.04.01 or higher.
  • The API requires this exact package: import androidx.compose.foundation.style.Style

2. Configure compiler options to enable experimental API

You must opt-in to the experimental API at the project level. Add the following block to your module's build.gradle.kts:

kotlin {    compilerOptions {        jvmTarget = JvmTarget.fromTarget("17")        freeCompilerArgs.add("-opt-in=androidx.compose.foundation.style.ExperimentalFoundationStyleApi")    }}

Core workflows and guides

Refer to the official documentation to complete specific development tasks:

  • Basic Style Usage: To set backgrounds, sizes, and alignments on a component, follow the Compose Styles Fundamentals Guide [blocked].
  • State and Transitions: To configure property changes for state shifts (like pressed or hovered), follow the Animations and State-Based Styling Guide [blocked].
  • Architecture Trade offs: To decide when to use a Style versus a standard Modifier, follow the Styles versus Modifiers Comparison [blocked].
  • Theme Level Integration: To connect style definitions with custom themes, follow Theming with Styles [blocked] and Custom Themes in Compose [blocked].

Step-by-Step Migration Workflow

Step 1: Analyze theme structure

  1. Locate your central theme file (such as Theme.kt).
  2. Identify design tokens. Note references for colors, typography, and shapes (for example, LocalColorScheme, LocalTypography, or LocalShapes).
  3. If the project lacks Jetpack Compose dependencies, stop. Instruct the user to migrate to Jetpack Compose first.
  4. If the project imports androidx.compose.material.MaterialTheme, recommend migrating to Material 3 before proceeding.

Step 2: Establish ComponentStyles

  1. Create a new file named ComponentStyles.kt in your theme directory.

  2. Define a top-level data class to hold your component styles, for example, the Jetsnack one is called JetsnackStyles:

    kotlin
    object ExampleComponentStyles {    val customButtonStyle: Style = {
        }    val customTextFieldStyle: Style = {
        }}
    <br />
  3. Expose this class through your custom theme with a static reference, don't use CompositionLocals here as it's not required.

    kotlin
    @Immutableclass JetsnackTheme(    // other Design system properties) {    companion object {        val colors: CustomThemingWithStyles.JetsnackColors            @Composable @ReadOnlyComposable            get() = LocalJetsnackTheme.current.colors        // ...
            // add helper static reference        val styles: ComponentStyles = ComponentStyles    }}
    <br />
  4. Provide extensions on StyleScope to reference theme tokens directly if they are exposed using CompositionLocals. For example:

    kotlin
    val StyleScope.colors: JetsnackColors    get() = LocalJetsnackTheme.currentValue.colors
    val StyleScope.typography: androidx.compose.material3.Typography    get() = LocalJetsnackTheme.currentValue.typography
    val StyleScope.shapes: Shapes    get() = LocalJetsnackTheme.currentValue.shapes
    <br />

Step 3: Migrate a component to Styles API

For each custom component (for example, CustomButton), complete the following sequence:

  1. Establish a visual baseline (If an emulator is available):
    • If you CANNOT run an Android emulator: Skip this step entirely and proceed to Step 2.
    • If you CAN run an Android emulator: Perform the following to capture a baseline screenshot:
      • Option A: Locate and run an existing screenshot test for the component.
      • Option B (If no test exists): Create a test using the project's existing testing framework, then run it.
      • Option C (If no framework exists): Create a minimal screenshot test using UI Automator or Espresso, then run it.
  2. Remove individual styling parameters : Remove styling parameters such as backgroundColor, shape, textStyle, and contentPadding from the signature - anything that StyleScope supports.
  3. Add the style parameter : Add style: Style = Style to the function signature. Always ensure the default value is exactly Style (e.g., style: Style = Style) and not a specific style default like ChipStyleDefault or any other value.
  4. Declare state tracking : If the component is interactable, create a MutableStyleState using the interaction source. Update state fields (such as isEnabled) inside the Composable to track the state correctly.
  5. Apply styleable modifier : Replace specific layout modifiers on the root element with Modifier.styleable().
  6. Move defaults to ComponentStyles : Move hardcoded values from the component definition to a dedicated Style instance in ComponentStyles.kt.
  7. Validate component: Compare the baseline screenshot image taken at the start with the rendered Compose Preview of the new composable. Ignore string content; focus on layout and styling. Iterate on the Compose code until visual parity is achieved. Once verified, write a Compose UI test for the new composable.
Migration example

Before Migration:

kotlin
@Composablefun CustomButton(    onClick: () -> Unit,    modifier: Modifier = Modifier,    backgroundColor: Color = JetsnackTheme.colors.brandLight,    disabledBackgroundColor: Color = JetsnackTheme.colors.brandSecondary,    shape: Shape = JetsnackTheme.shapes.extraLarge,    textStyle: TextStyle = JetsnackTheme.typography.labelLarge,    enabled: Boolean = true,    content: @Composable RowScope.() -> Unit,) {    val interactionSource = remember { MutableInteractionSource() }    Row(        modifier            .clickable(onClick = onClick, indication = null, interactionSource = interactionSource)            .background(if (enabled) backgroundColor else disabledBackgroundColor, shape)            .defaultMinSize(58.dp, 40.dp),        horizontalArrangement = Arrangement.Center,        verticalAlignment = Alignment.CenterVertically,        content = content,    )}
<br />

After Migration:

kotlin
// Exposed via ComponentStyles.ktobject ComponentStyles {    val buttonStyle = Style {        background(colors.brandLight)        shape(shapes.extraLarge)        minWidth(58.dp)        minHeight(40.dp)        textStyle(typography.labelLarge)        disabled {            background(colors.brandSecondary)        }    }}
@Composablefun CustomButton(    onClick: () -> Unit,    modifier: Modifier = Modifier,    style: Style = Style,    enabled: Boolean = true,    content: @Composable RowScope.() -> Unit,) {    val interactionSource = remember { MutableInteractionSource() }    val styleState = rememberUpdatedStyleState(interactionSource) {        it.isEnabled = enabled    }    Row(        modifier            .clickable(onClick = onClick, indication = null, interactionSource = interactionSource)            .styleable(styleState, JetsnackTheme.styles.buttonStyle, style),        horizontalArrangement = Arrangement.Center,        verticalAlignment = Alignment.CenterVertically,        content = content,    )}
<br />

Step 4: Validate Changes

  1. Build the project. Verify that there are no compilation errors.
  2. Run your module's screenshot tests.
  3. Compare visual outputs of the whole app between the previous and updated components. Verify that no visual layout regressions occur.

來源與署名

來源:android/skills位於jetpack-compose/theming/styles提交42dc227

授權條款: Complete terms in LICENSE.txt

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 android/skills 的技能

Wear Compose M3

android

指導建置、更新與移轉 Wear OS Compose Material3 應用程式,並提供標準元件範例與版本規則。

Software Development7.7K13 天前更新

Display Glasses With Jetpack Compose Glimmer

android

Provides guidelines for developing projected Android XR apps for display glasses using the Jetpack Compose Glimmer UI toolkit. This skill covers foundational Glimmer design principles, workflows for implementing Jetpack Compose Glimmer, and interaction models for the glasses form factor. Use this skill to build an Android XR Augmented Experience app with Jetpack Compose Glimmer that adheres to the Glimmer design system for optimized glasses styling.

待分類7.7K13 天前更新

Play Billing Library Version Upgrade

android

引導將 Android 專案從舊版 Google Play 帳務程式庫升級到最新穩定版本。

Software Development7.7K13 天前更新

Leanback To Compose Tv Migration

android

Provides instructions and architectural patterns for migrating Android TV applications from legacy Leanback UI Toolkit, Android Views, or Support Fragments to Jetpack Compose for TV (androidx.tv). Use this skill for Leanback to Compose migrations, including browse screen, settings screen, authentication screen, login screen, or video playback screen migrations, or when replacing BrowseSupportFragment, LeanbackSettingsFragment, PreferenceFragment, BaseLeanbackPreferenceFragmentCompat, VideoSupportFragment, GuidedStepSupportFragment, SearchSupportFragment, VerticalGridSupportFragment, Presenter, ArrayObjectAdapter, or CursorMapper with modern Compose equivalents, implementing immersive carousels with focus memory, Media3 video playback with PlayerSurface, or custom 10-foot hero layouts.

待分類7.7K13 天前更新

Testing Setup

android

分析 Android 專案的測試設定,並安裝測試框架、測試基礎設施,以及單元、UI、截圖與端對端測試。

Software Development7.7K13 天前更新

Android Profiler

android

引導 Android 效能分析:錄製系統追蹤、堆積轉儲與方法記錄,並以 Perfetto SQL 進行分析。

Software Development7.7K13 天前更新