可用于学习和演示跨平台 UI 开发,展示 Kotlin Multiplatform 与 Compose Multiplatform 在 Android、iOS、HarmonyOS 的应用。包含多标签导航、组件库分组展示、性能测试及平台互操作等功能,支持共享 UI 代码与扩展组件示例。【此简介由AI生成】
| Files | Last commit | Last 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.ktDialogDemo.kt,PopupDemo.kt,LayoutDemo.ktLazyLayoutDemo.kt,SubcomposeLayoutDemo.ktMultiMeasureLayoutDemo.kt,PathDemo.ktRenderVectorGroupDemo.kt,GroupDemo.ktInterceptPlatformTextInputDemo.kt,MenuItemDemo.ktMultiInstanceDemo.kt,AccessibilityTestPage.kt
-
Foundation group includes but is not limited to the following demo pages (directory:
demos/foundation/):BasicSecureTextFieldDemo.kt,BasicTextDemo.kt,BasicTextFieldDemo.ktBasicTooltipBoxDemo.kt,CanvasDemo.kt,ClickableTextDemo.ktDecorationDemo.kt,DisableSelectionDemo.kt,HorizontalPagerDemo.ktVerticalPagerDemo.kt,ImageDemo.kt,ItemDemo.ktLazyColumnDemo.kt,LazyRowDemo.kt,LazyHorizontalGridDemo.ktLazyVerticalGridDemo.kt,LazyHorizontalStaggeredGridDemo.ktLazyVerticalStaggeredGridDemo.kt,LazyLayoutPinnableItemDemo.ktScrollableDemo.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.ktBadgeDemo.kt,BottomAppBarDemo.kt,BottomDrawerDemo.ktBottomNavigationDemo.kt,BottomSheetScaffoldDemo.kt,ButtonDemo.ktCardDemo.kt,ChipDemo.kt,ContentAlphaDemo.kt,CustomFontDemo.ktDividerDemo.kt,DrawerDemo.kt,ElevationDemo.ktExposedDropdownMenuDemo.kt,FloatingActionButtonDemo.kt,IconButtonDemo.ktIconDemo.kt,LeadingIconTabDemo.kt,ListDemo.kt,MenuDemo.ktModalBottomSheetDemo.kt,NavigationRailDemo.kt,OutlinedButtonDemo.ktOutlinedSecureTextFieldDemo.kt,OutlinedTextFieldDecorationBoxDemo.ktProgressIndicatorDemo.kt,ProvideTextStyleDemo.kt,PullRefreshDemo.ktScaffoldDemo.kt,SecureTextFieldDemo.kt,SelectionControlsDemo.ktSliderDemo.kt,SnackbarDemo.kt,SnackbarHostDemo.kt,SurfaceDemo.ktSwipeToDismissDemo.kt,SwipeableDemo.kt,TabDemo.kt,TextButtonDemo.ktTextDemo.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 itemsCompose1500view.kt: Scroll performance test with 1500 Box itemsDmaOptimizationDemo.kt: DMA optimization demoLargeImage.kt: Large image loading testNestedMixedLayout.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
commonMaindependencies incomposeApp/build.gradle.kts. - Material (Legacy Material Components): Add
implementation(compose.material)tocommonMain. - 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
- Compile and publish Shared Library to the HarmonyOS project directory:
./gradlew :composeApp:publishDebugBinariesToHarmonyApp - Open the
harmonyAppdirectory with DevEco Studio. - Sync the project in DevEco Studio and run on a HarmonyOS device or emulator.
- Compile and publish Shared Library to the HarmonyOS project directory:
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
viewIdpassed on the Kotlin side must strictly match the first argument ofregisterComposeInteropBuilderon the ArkTS side. - Layout Constraints: It is recommended to explicitly specify size using
Modifieron 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 AlertDialogSamplesM2import com.example...demos.material3.AlertDialogSamples as AlertDialogSamplesM3
- All Material3 sample functions are uniformly named
-
Necessary Imports
import androidx.compose.ui.Modifierimport 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.*(whenRow/Column/Box/padding/size/Arrangementetc. 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)
- Adding at the top of the file:
- Some components in Material3 (
-
Gestures & Scrolling
- Material (M2) can use
SwipeToDismiss; Material3 version can useSwipeToDismissBox(depending on version). - Basic gesture layer replacement:
AnchoredDraggableState+anchoredDraggable(foundation), avoiding the removedswipeableseries.
- Material (M2) can use
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) samplesdemos/material3/*: Material3 samples (uniformly namedXXXSamplesM3())
Navigation & Display
- The home page displays the
componentDemoslist fromnavigation/Navigation.ktby group. DemoScreen(demo: ComponentDemo)routes to the corresponding sample based ondemo.id.- All Material3 samples are integrated with unified titles and routing.
Common Errors
Unresolved reference 'Modifier'/'dp'/'sp': Missing necessary imports, refer to above.SmallTopAppBarunresolved: UseTopAppBaror 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:
- Symbol Resolution Error: The
napi_init.cppin the Native layer failed to correctly load Compose's initialization functionandroidx_compose_ui_arkui_init. - Controller Initialization Timing: Attempting to create
ArkUIViewControllerbefore the Native module is fully loaded, or not initializing it correctly in theaboutToAppearlifecycle. - Missing Library Name: Correct
libraryNamewas not specified in the ArkTSComposecomponent.
Solution:
-
Fix
napi_init.cpp: Ensure the dynamic symbol lookup includes a fallback mechanism (compatible with different versions of symbol names) and usesdlsym(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); } // ... } -
Correct Controller Initialization (
Index.ets): ChecknativeApiand initialize the Controller inaboutToAppear, 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)); } } } -
Specify Library Name: Explicitly pass
libraryName(usually'entry'or your dynamic library name) when using theComposecomponent.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 inlibs.versions.toml. - Confirm alias spelling. For example,
compose-multiplatform-exportshould be referenced aslibs.compose.multiplatform.exportin 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