开发环境
教程
深入详解 Jetpack Compose | 实现原理
实际开发体验和flutter很像,但是实际原理好像不同,flutter中组件都是widget对象,比较容易理解
而compose中组件并没有返回值,编译器会对@Composable
的方法进行处理,具体原理需要深入了解
@Composable
官方说明
关于@Composable
,有几点值得注意:
- 此函数带有 @Composable 注释。所有可组合函数都必须带有此注释;此注释可告知 Compose 编译器:此函数旨在将数据转换为界面。
- 此函数接受数据。可组合函数可以接受一些参数,这些参数可让应用逻辑描述界面。在本例中,我们的微件接受一个 String,因此它可以按名称问候用户。
- 此函数可以在界面中显示文本。为此,它会调用 Text() 可组合函数,该函数实际上会创建文本界面元素。可组合函数通过调用其他可组合函数来发出界面层次结构。
- 此函数不会返回任何内容。发出界面的 Compose 函数不需要返回任何内容,因为它们描述所需的屏幕状态,而不是构造界面微件。
- 此函数快速、幂等且没有副作用。
- 使用同一参数多次调用此函数时,它的行为方式相同,并且它不使用其他值,如全局变量或对 random() 的调用。
- 此函数描述界面而没有任何副作用,如修改属性或全局变量。
一般来说,出于重组部分所述的原因,所有可组合函数都应使用这些属性来编写。
依赖
dependencies {
def lifecycle_version = "2.3.1"
def compose_version = '1.0.0-beta01'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Jetpack Compose Integration for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04"
implementation "androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha03"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-rc01'
implementation 'androidx.activity:activity-compose:1.3.0-alpha02'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation "androidx.compose.ui:ui-tes