插件
Jetpack Compose
@nativescript/jetpack-compose
一个允许您在 NativeScript 中使用 Jetpack Compose 的插件。
内容
安装
cli
npm install @nativescript/jetpack-compose
使用 @nativescript/jetpack-compose
添加 Jetpack Compose 版本和依赖项
调整 App_Resources/Android/app.gradle
以包含您所需的 Jetpack Compose 版本和依赖项
ts
dependencies {
def compose_version = "1.2.1"
implementation "androidx.compose.ui:ui:$compose_version"
// Tooling support (Previews, etc.)
implementation "androidx.compose.ui:ui-tooling:$compose_version"
// Add any other dependencies your Jetpack Compose UI needs
}
android {
// other settings like targetSdk, etc.
buildFeatures {
compose true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.2'
}
}
创建 Compose 视图
可以在您的 App_Resources 中创建任何 Kotlin 文件,例如
App_Resources/Android/src/main/java/BasicView.kt
java
class BasicView {
data class ExampleUIState(
val text: String = ""
) {}
class ExampleViewModel(
) : ViewModel() {
var uiState by mutableStateOf(ExampleUIState())
}
var mViewModel = ExampleViewModel()
fun generateComposeView(view: ComposeView): ComposeView {
return view.apply {
setContent {
MaterialTheme {
val uiState = mViewModel.uiState;
Text(uiState.text)
}
}
}
}
fun updateData(value: Map<Any, Any>) {
val v = value["data"] as String;
onEvent?.invoke(v)
mViewModel.uiState = ExampleUIState(v);
}
var onEvent: ((String) -> Unit)? = null
}
注册您的 Compose 视图
这可以在引导文件(通常是 app.ts
或 main.ts
)甚至需要它的视图组件中完成。
app.ts
typescript
import {
registerJetpackCompose,
ComposeDataDriver,
} from '@nativescript/jetpack-compose'
// A. You can generate types for your own Compose Provider with 'ns typings android --aar {path/to/{name}.aar}'
// B. Otherwise you can ignore by declaring the package resolution path you know you provided
declare var com
registerJetpackCompose(
'flyingHearts',
(view) => new ComposeDataDriver(new com.example.FlyingHearts(), view)
)
将 Compose 视图与任何 NativeScript 布局一起使用
这说明了通常称为“原生”风格的 NativeScript 应用。但是,您可以将此插件与任何风格(Angular、React、Svelte、Vue 等)一起使用。
xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo" class="page" xmlns:jc="@nativescript/jetpack-compose">
<StackLayout>
<jc:JetpackCompose composeId="flyingHearts" composeEvent="{{ onEvent }}" data="{{ text }}"/>
</StackLayout>
</Page>
将 Jetpack Compose 与 Angular 一起使用
ts
import { registerElement } from '@nativescript/angular'
import { JetpackCompose } from '@nativescript/jetpack-compose'
registerElement('JetpackCompose', () => JetpackCompose)
现在它可以在任何 Angular 组件中使用,例如
xml
<StackLayout>
<JetpackCompose composeId="flyingHearts" (composeEvent)="onEvent($event)" [data]="data"></JetpackCompose>
</StackLayout>
鸣谢
NativeScript 荣幸地得到 Valor Software 作为官方合作伙伴的支持。我们很自豪能够在 NativeScript 的所有方面提供指导、咨询和开发协助。
许可证
MIT