kmptpc_compose_sample:基于 Kotlin Multiplatform 与 Compose Multiplatform 的跨平台组件示例项目

可用于学习和演示跨平台 UI 开发,展示 Kotlin Multiplatform 与 Compose Multiplatform 在 Android、iOS、HarmonyOS 的应用。包含多标签导航、组件库分组展示、性能测试及平台互操作等功能,支持共享 UI 代码与扩展组件示例。【此简介由AI生成】

Branch2Tags0
FilesLast commitLast update
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
4 months ago
5 months ago
5 months ago
5 months ago

KMP Compose Sample

English | 简体中文

Version Information

Component Version
Kotlin 2.2.21-ohos-01
Compose Multiplatform 1.9.2-eazytec-001
Gradle 8.14.3
Android Gradle Plugin 8.11.2
Android SDK Compile 36 / Min 24 / Target 36

A sample project using Kotlin Multiplatform + Compose Multiplatform, targeting Android, iOS, and HarmonyOS. This project demonstrates component navigation and property showcase grouped by library, including:

  • compose.ui (UI Components)
  • compose.foundation (Foundation Components)
  • compose.material (Material Design Components)
  • compose.material3 (Material Design 3 Components)
  • Performance Benchmark (Performance Benchmark Testing)
  • Platform Interop Demo (Platform-specific features, e.g., HarmonyOS Interop)
  • Self Rendering Demo (Self-rendering functionality)

The application features a bottom navigation bar with three main tabs:

  • Basic Tab: Component library with grouped navigation and detailed property demos
  • ov-compose Tab: Open-source Compose components and custom implementations
  • kotlin Samples Tab: Official Kotlin samples and examples

Features

  • Three-Tab Navigation: Bottom navigation with distinct functional areas
  • Basic Tab: Grouped component navigation with search functionality
  • ov-compose Tab: Custom Compose components and advanced implementations
  • kotlin Samples Tab: Official Kotlin examples and best practices
  • Cross-Platform: Shared UI code, running synchronously on Android, iOS, and HarmonyOS with a single Compose codebase
  • Extensible: Support adding more components and examples to each tab

Directory Structure

  • composeApp/src/commonMain/kotlin/com/example/kmptpc_compose_sample/
    • App.kt: App entry point, handling group lists and page navigation.
    • demos/ComponentData.kt: Component data models and group definitions.
    • demos/ComponentsScreen.kt: Component list page.
    • demos/ComponentDetailScreen.kt: Component detail demo page.
    • demos/ui/: UI group demo pages directory.
    • demos/foundation/: Foundation group demo pages directory.
    • demos/material/: Material group demo pages directory.
    • demos/render/: Rendering-related demo pages directory.
    • demos/gesture/: Gesture-related demo pages directory.
    • demos/benchmark/: Performance benchmark demo pages directory.
    • navigation/NaviBackHandler.kt: Navigation back handler.
    • official/: Official sample pages.
  • composeApp/src/androidMain/kotlin/com/example/kmptpc_compose_sample/MainActivity.kt: Android entry point.
  • composeApp/src/androidMain/kotlin/com/example/kmptpc_compose_sample/ovcompose/backhandler/BackHandler.android.kt: Android platform-specific functionality.

Component Demo Navigation

  • Group titles use simplified library names (e.g., compose.ui).

  • Clicking a component list item navigates to the demo page, which includes:

    • Common property controls (enabled state, size, color, shape, shadow, etc.)
    • Interactive examples (click counters, scrolling lists, etc.)
  • UI group includes but is not limited to the following demo pages (directory: demos/ui/):

    • BoxDemo.kt, ColumnDemo.kt, RowDemo.kt
    • DialogDemo.kt, PopupDemo.kt, LayoutDemo.kt
    • LazyLayoutDemo.kt, SubcomposeLayoutDemo.kt
    • MultiMeasureLayoutDemo.kt, PathDemo.kt
    • RenderVectorGroupDemo.kt, GroupDemo.kt
    • InterceptPlatformTextInputDemo.kt, MenuItemDemo.kt
    • MultiInstanceDemo.kt, AccessibilityTestPage.kt
  • Foundation group includes but is not limited to the following demo pages (directory: demos/foundation/):

    • BasicSecureTextFieldDemo.kt, BasicTextDemo.kt, BasicTextFieldDemo.kt
    • BasicTooltipBoxDemo.kt, CanvasDemo.kt, ClickableTextDemo.kt
    • DecorationDemo.kt, DisableSelectionDemo.kt, HorizontalPagerDemo.kt
    • VerticalPagerDemo.kt, ImageDemo.kt, ItemDemo.kt
    • LazyColumnDemo.kt, LazyRowDemo.kt, LazyHorizontalGridDemo.kt
    • LazyVerticalGridDemo.kt, LazyHorizontalStaggeredGridDemo.kt
    • LazyVerticalStaggeredGridDemo.kt, LazyLayoutPinnableItemDemo.kt
    • ScrollableDemo.kt, SelectionContainerDemo.kt, SpacerDemo.kt
  • Material group includes but is not limited to the following demo pages (directory: demos/material/):

    • AlertDialogDemo.kt, AppBarDemo.kt, BackdropScaffoldDemo.kt
    • BadgeDemo.kt, BottomAppBarDemo.kt, BottomDrawerDemo.kt
    • BottomNavigationDemo.kt, BottomSheetScaffoldDemo.kt, ButtonDemo.kt
    • CardDemo.kt, ChipDemo.kt, ContentAlphaDemo.kt, CustomFontDemo.kt
    • DividerDemo.kt, DrawerDemo.kt, ElevationDemo.kt
    • ExposedDropdownMenuDemo.kt, FloatingActionButtonDemo.kt, IconButtonDemo.kt
    • IconDemo.kt, LeadingIconTabDemo.kt, ListDemo.kt, MenuDemo.kt
    • ModalBottomSheetDemo.kt, NavigationRailDemo.kt, OutlinedButtonDemo.kt
    • OutlinedSecureTextFieldDemo.kt, OutlinedTextFieldDecorationBoxDemo.kt
    • ProgressIndicatorDemo.kt, ProvideTextStyleDemo.kt, PullRefreshDemo.kt
    • ScaffoldDemo.kt, SecureTextFieldDemo.kt, SelectionControlsDemo.kt
    • SliderDemo.kt, SnackbarDemo.kt, SnackbarHostDemo.kt, SurfaceDemo.kt
    • SwipeToDismissDemo.kt, SwipeableDemo.kt, TabDemo.kt, TextButtonDemo.kt
    • TextDemo.kt, TextFieldDecorationBoxDemo.kt, TextFieldDemo.kt, ThemeDemo.kt
  • Rendering group includes (directory: demos/render/):

    • CanvasBasicDrawingDemo.kt, PathDrawingDemo.kt, TextDrawingDemo.kt, ImageDrawingDemo.kt
  • Gesture group includes (directory: demos/gesture/):

    • GestureDemo.kt
  • Benchmark group includes (cross-platform, directory: demos/benchmark/):

    • Compose1500Text.kt: Scroll performance test with 1500 Text items
    • Compose1500view.kt: Scroll performance test with 1500 Box items
    • DmaOptimizationDemo.kt: DMA optimization demo
    • LargeImage.kt: Large image loading test
    • NestedMixedLayout.kt: Nested mixed layout test

You can supplement/refine the "full property effects" for each demo page as needed.

Dependencies

  • Compose Runtime/Foundation/UI/Material3: Included in commonMain dependencies in composeApp/build.gradle.kts.
  • Material (Legacy Material Components): Add implementation(compose.material) to commonMain.
  • Others: AndroidX Lifecycle, etc., included as needed.

Build & Run

  • Android (Recommended: Run in Android Studio or via command line):

    ./gradlew :composeApp:assembleDebug
    
  • Windows:

    .\gradlew.bat :composeApp:assembleDebug
    
  • iOS Build & Run Use the run configuration in the IDE toolbar to build and run the iOS development version, or open the /iosApp directory in Xcode and run.

  • HarmonyOS Build & Run

    1. Compile and publish Shared Library to the HarmonyOS project directory:
      ./gradlew :composeApp:publishDebugBinariesToHarmonyApp
      
    2. Open the harmonyApp directory with DevEco Studio.
    3. Sync the project in DevEco Studio and run on a HarmonyOS device or emulator.

Using ArkUI-TS in Compose Multiplatform (Interop)

This project supports embedding native ArkTS components (such as XComponent, List, etc.) into Compose layouts on the HarmonyOS platform.

1. ArkTS Side: Definition & Registration

Create a component file (e.g., ComposeInterops.ets) in entry/src/main/ets/pages/, define a Builder function, and register it to the Compose interop table.

// ComposeInterops.ets
import { registerComposeInteropBuilder } from './ComposeSample'

@Builder
function InteropExample() {
  Column() {
    Text('I am a native ArkTS component')
  }
  .width('100%')
  .height('100vp')
  .backgroundColor(Color.Yellow)
}

// Register Builder, the name "InteropExample" must match the Kotlin side
export function registerComposeInteropBuilders() {
  registerComposeInteropBuilder("InteropExample", wrapBuilder(InteropExample));
}

Call the registration function during Index.ets or app entry initialization:

// Index.ets
import { registerComposeInteropBuilders } from './ComposeInterops';

aboutToAppear() {
  registerComposeInteropBuilders();
  // ... other initialization
}

2. Kotlin Side: Usage

In composeApp/src/ohosMain/kotlin, use the ArkUIView wrapper (or similar implementation) to load the registered ArkTS component.

// Usage Example
@Composable
fun ArkTSInteropExample() {
    Column {
        Text("Below is an ArkTS Component:")
        
        // "InteropExample" corresponds to the name registered on the ArkTS side
        ArkUIView(
            viewId = "InteropExample", 
            modifier = Modifier.fillMaxWidth().height(100.dp)
        )
    }
}

Notes:

  • ID Consistency: The viewId passed on the Kotlin side must strictly match the first argument of registerComposeInteropBuilder on the ArkTS side.
  • Layout Constraints: It is recommended to explicitly specify size using Modifier on the Kotlin side (e.g., .height(100.dp)), otherwise it may not display due to measurement modes.

Learn more about Kotlin Multiplatform…

Material3 Naming Conventions & Common Errors

  • Naming Conventions

    • All Material3 sample functions are uniformly named XXXSamplesM3() to avoid overload resolution ambiguity with Material (M2) functions of the same name.
    • If you need to keep the same name, use import aliases at the call site:
      • import com.example...demos.material.AlertDialogSamples as AlertDialogSamplesM2
      • import com.example...demos.material3.AlertDialogSamples as AlertDialogSamplesM3
  • Necessary Imports

    • import androidx.compose.ui.Modifier
    • import androidx.compose.ui.unit.dp (when size units are needed)
    • import androidx.compose.ui.unit.sp (when font size units are needed)
    • import androidx.compose.foundation.layout.* (when Row/Column/Box/padding/size/Arrangement etc. are needed)
    • If using alignment: import androidx.compose.ui.Alignment
  • Opt-in for Experimental APIs

    • Some components in Material3 (ModalBottomSheet, DatePicker, TimePicker, SearchBar, etc.) require:
      • Adding at the top of the file: @file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
  • Gestures & Scrolling

    • Material (M2) can use SwipeToDismiss; Material3 version can use SwipeToDismissBox (depending on version).
    • Basic gesture layer replacement: AnchoredDraggableState + anchoredDraggable (foundation), avoiding the removed swipeable series.

Directory Structure (Example)

  • demos/ui/*: UI group samples (e.g., BoxDemo.kt)
  • demos/foundation/*: Foundation group samples (e.g., BasicTextDemo.kt, LazyColumnDemo.kt)
  • demos/material/*: Material (M2) samples
  • demos/material3/*: Material3 samples (uniformly named XXXSamplesM3())
  • The home page displays the componentDemos list from navigation/Navigation.kt by group.
  • DemoScreen(demo: ComponentDemo) routes to the corresponding sample based on demo.id.
  • All Material3 samples are integrated with unified titles and routing.

Common Errors

  • Unresolved reference 'Modifier'/'dp'/'sp': Missing necessary imports, refer to above.
  • SmallTopAppBar unresolved: Use TopAppBar or other M3 top bar components.
  • Experimental APIs (DatePicker, TimePicker, ModalBottomSheet, SearchBar, etc.): Add at the top of the file
    • @file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)

HarmonyOS Common Issues & Solutions

1. Runtime Crash: ArkUIViewController_setId or Not mapped Error

Symptom: App crashes immediately upon launch or navigation to a Compose page, with logs containing ArkUIViewController_setId, Not mapped, or libComposeApp.so related errors.

Cause:

  1. Symbol Resolution Error: The napi_init.cpp in the Native layer failed to correctly load Compose's initialization function androidx_compose_ui_arkui_init.
  2. Controller Initialization Timing: Attempting to create ArkUIViewController before the Native module is fully loaded, or not initializing it correctly in the aboutToAppear lifecycle.
  3. Missing Library Name: Correct libraryName was not specified in the ArkTS Compose component.

Solution:

  1. Fix napi_init.cpp: Ensure the dynamic symbol lookup includes a fallback mechanism (compatible with different versions of symbol names) and uses dlsym(RTLD_DEFAULT, ...).

    // entry/src/main/cpp/napi_init.cpp
    typedef void (*init_fn)(napi_env, napi_value);
    
    static napi_value Init(napi_env env, napi_value exports) {
        // Try loading new version symbol
        init_fn fn = reinterpret_cast<init_fn>(dlsym(RTLD_DEFAULT, "androidx_compose_ui_arkui_utils_init"));
        if (fn == nullptr) {
            // Fallback to old version symbol
            fn = reinterpret_cast<init_fn>(dlsym(RTLD_DEFAULT, "androidx_compose_ui_arkui_init"));
        }
        if (fn != nullptr) {
            fn(env, exports);
        }
        // ...
    }
    
  2. Correct Controller Initialization (Index.ets): Check nativeApi and initialize the Controller in aboutToAppear, adding exception handling.

    // entry/src/main/ets/pages/Index.ets
    aboutToAppear() {
      if (nativeApi) {
        try {
          this.controller = nativeApi.MainArkUIViewController();
        } catch (e) {
          hilog.error(DOMAIN, 'Compose', 'Controller creation failed: %{public}s', JSON.stringify(e));
        }
      }
    }
    
  3. Specify Library Name: Explicitly pass libraryName (usually 'entry' or your dynamic library name) when using the Compose component.

    Compose({
      controller: this.controller,
      libraryName: 'entry', // Must be specified
      onBackPressed: () => false
    })
    

2. Build Error: input file does not exist (:cinteropResourceOhosArm64)

Cause: The resource.def file location does not match the path configured in build.gradle.kts. Solution: Ensure the file is located at src/ohosMain/cinterop/resource.def, or adjust the defFile(file(...)) path configuration.

3. Dependency Conflict: Variant mismatch / 403 Forbidden

Cause: Some AndroidX libraries (like lifecycle, savedstate) are not fully adapted to the OHOS target, causing Gradle to pull incorrect artifacts or face permission issues during resolution. Solution: Exclude conflicting groups in the ohos configuration in build.gradle.kts:

configurations.all {
    if (name.contains("ohos", ignoreCase = true)) {
        exclude(group = "org.jetbrains.androidx.lifecycle")
        exclude(group = "org.jetbrains.androidx.savedstate")
    }
}

4. ArkTS Button Syntax in Mixed Rendering (Interop)

Symptom: When mixing Compose and ArkTS (e.g., embedding ArkTS components in LazyColumn), buttons using the Button('Text', { type: ButtonType.Normal }) syntax may exhibit rendering anomalies or layout errors.

Cause: The layout measurement mechanism in mixed rendering scenarios may not fully support certain ArkTS shorthand forms.

Solution: Uniformly use the container syntax to define Buttons:

// Recommended Syntax (Interop Scenarios)
Button({ type: ButtonType.Normal }) {
  Text('Ark Button')
    .fontSize(16)
    .fontColor(Color.White)
}
.borderRadius(2)
.height('100vp')

// Avoid using
// Button('Ark Button', { type: ButtonType.Normal }) ...

Gradle Build Common Issues & Pitfalls Guide

1. Unresolved reference Error

Symptom: build.gradle.kts reports Unresolved reference: libs.xxx. Cause: The corresponding library or plugin alias is not defined in libs.versions.toml, or the alias spelling is inconsistent (Gradle converts - in TOML to .). Solution:

  • Check the [libraries] and [plugins] blocks in libs.versions.toml.
  • Confirm alias spelling. For example, compose-multiplatform-export should be referenced as libs.compose.multiplatform.export in Kotlin DSL.

2. Skiko Version Incompatibility

Symptom: OHOS runtime crash or rendering exception, indicating Skiko version issues. Cause: The default Skiko version depended on by Compose Multiplatform may not be adapted to the specific OHOS version. Solution: Force a specific Skiko version in build.gradle.kts:

resolutionStrategy {
    eachDependency {
        if (requested.group == "org.jetbrains.skiko" && requested.name == "skiko") {
             if (configName.contains("ohos", ignoreCase = true)) {
                 useVersion("0.9.22.2-ez-001") // Use adapted version
             }
        }
    }
}

3. Dependency Conflict: androidx.collection

Symptom: Build failure indicating dependency version conflict. Cause: Different libraries depend on different versions of androidx.collection. Solution: Force a specific version and exclude conflicting modules:

configurations.all {
    resolutionStrategy {
        eachDependency {
            if (requested.group == "androidx.collection" && requested.name == "collection") {
                useVersion(libs.versions.androidx.collection.get())
            }
        }
    }
    exclude(group = "androidx.collection", module = "collection-jvm")
}

Introduction

可用于学习和演示跨平台 UI 开发,展示 Kotlin Multiplatform 与 Compose Multiplatform 在 Android、iOS、HarmonyOS 的应用。包含多标签导航、组件库分组展示、性能测试及平台互操作等功能,支持共享 UI 代码与扩展组件示例。【此简介由AI生成】

Customize your domain