一、Compose 介紹
google 在 07月28日 發布了compose 1.0正式版,代表著其api結構已經趨于穩定,作為一個合格(天天劃水)的android developer,也是時候開始了解它了,
以下內容參考自官網內容
Jetpack Compose 是一個適用于 Android 的新式宣告性界面工具包,Compose 提供宣告性 API,讓您可在不以命令方式改變前端視圖的情況下呈現應用界面,從而使撰寫和維護應用界面變得更加容易,
二、Compose 創建
1.新建應用
- 下載安裝 Android Studio Arctic Fox,以便于在
Jetpack Compose進行開發時獲得最佳體驗 - 創建應用
New Project選擇Empty Compose Activity,然后Next,在填寫好相關資訊后Finish進入應用主界面,等待構建完成, - 在手機/模擬器上運行你的第一個
Compose
至此,compose 創建完成,工具下載及應用構建建議科學上網,
三、查看初始 Compose 應用結構
一個新建的Compose應用內包含了一個MainActivity.kt,以及ui.theme包內顏色、主題等組態檔
1. MainActivity
1.1. 父類
MainActivity繼承自 ComponentActivity,ComponentActivity 又繼承自 Activity,說明View還是通過setContentView()加載,
1.2. onCreate() 方法
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Compose_oneTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
Greeting()
}
}
}
}
方法內 setContent{}就比較陌生了,通過原始碼可以看到setContent()是ComponentActivity的一個拓展方法,其中的content引數需要傳入一個由@Composable注解的函式,值得注意的是@Composable并非傳統意義上的注解處理器,Compose 在 Kotlin 編譯器的型別檢測與代碼生成階段依賴 Kotlin 編譯器插件作業,所以無需注解處理器即可使用 Compose,@Composable的作用更像一個關鍵字,比如 suspend,@Composable 與其作業方式相同:它可以改變函式型別,重點是,當使用 @Composable 注解一個函式型別時,會導致它型別的改變:未被注解的相同函式型別與注解后的型別互不兼容,原始碼如下
public fun ComponentActivity.setContent(
parent: CompositionContext? = null,
content: @Composable () -> Unit
) {
val existingComposeView = window.decorView
.findViewById<ViewGroup>(android.R.id.content)
.getChildAt(0) as? ComposeView
if (existingComposeView != null) with(existingComposeView) {
setParentCompositionContext(parent)
setContent(content)
} else ComposeView(this).apply {
// Set content and parent **before** setContentView
// to have ComposeView create the composition on attach
setParentCompositionContext(parent)
setContent(content)
// Set the view tree owners before setting the content view so that the inflation process
// and attach listeners will see them already present
setOwners()
setContentView(this, DefaultActivityContentLayoutParams)
}
}
可以發現,在setContent內部,程式會去尋找Activity的根布局,若未找到則創建一個,然后將由@Conposable注解函式內的宣告式布局創建,
1.3. Greeting() 方法
@Composable
fun Greeting() {
Text(text = "Hello,Jetpack Compose!")
}
該方法由@Composable注解(最終需要傳入到setContent方法中的都需要注解,不論多少層),其內容則是要創建的視圖內容的具體宣告描述了,
1.4. DefaultPreview() 方法
@Preview(showBackground = true )
@Composable
fun DefaultPreview() {
Compose_oneTheme {
Greeting()
}
}
值得注意的是 DefaultPreview()除了添加了@Composable注解外,還添加了@Preview, @Preview注解的方法可以在不運行App的情況下就可以確認布局的情況,
如下圖所示

@Preview的注解中比較常用的引數如下:
name: String: 為該Preview命名,該名字會在布局預覽中顯示,showBackground: Boolean: 是否顯示背景,true為顯示,backgroundColor: Long: 設定背景的顏色,showDecoration: Boolean: 是否顯示Statusbar和Toolbar,true為顯示,group: String: 為該Preview設定group名字,可以在UI中以group為單位顯示,fontScale: Float: 可以在預覽中對字體放大,范圍是從0.01,- widthDp: Int: 在Compose中渲染的最大寬度,單位為dp,heightDp: Int: 在Compose中渲染的最大高度,單位為dp,
注意:強烈建議您不要向生產函式(即使其不帶引數)添加 @Preview 注釋,而是撰寫一個封裝函式并在其中添加 @Preview 注釋, 這便是 DefaultPreview存在的意義,詳見 developer.android.google.cn/jetpack/com…
2. ui.theme 包
包內包含了Color.kt、Shape.kt、Type.kt、Theme.kt,分別是顏色、形狀、型別、主題的描述檔案,可以理解為代替了傳統android專案內res內的xml組態檔;在后面的文章中會專門講到,
四、在現有應用中使用 Compose
1. 添加依賴
- 將
Gradle升級至7.0
buildscript {
...
dependencies {
classpath "com.android.tools.build:gradle:7.0.0"
...
}
}
- 將
Kotlin升級至1.5.21 - 配置
Gradle
需要將應用的最低 API 級別設定為 21 或更高級別,并在應用的 build.gradle 檔案中啟用 Jetpack Compose,如下所示,另外還要設定 Kotlin 編譯器插件的版本,
android {
defaultConfig {
...
minSdkVersion 21
}
buildFeatures {
// Enables Jetpack Compose for this module
compose true
}
...
// Set both the Java and Kotlin compilers to target Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
composeOptions {
kotlinCompilerExtensionVersion '1.0.1'
kotlinCompilerVersion '1.5.21'
}
}
- 添加
Jetpack Compose工具包依賴項
dependencies {
// Integration with activities
implementation 'androidx.activity:activity-compose:1.3.1'
// Compose Material Design
implementation 'androidx.compose.material:material:1.0.1'
// Animations
implementation 'androidx.compose.animation:animation:1.0.1'
// Tooling support (Previews, etc.)
implementation 'androidx.compose.ui:ui-tooling:1.0.1'
// Integration with ViewModels
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07'
// UI Tests
androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.0.1'
}
2. 在XML中使用Compopse
在xml中可以將 ComposeView 作為一個普通的view來使用,然后在代碼內通過setContent方法注入compose
<...>
<!-- Other content -->
<androidx.compose.ui.platform.ComposeView
android:id="@+id/greeting"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</...>
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
val greeting = findViewById<ComposeView>(R.id.greeting)
greeting.setContent {
MdcTheme { // or AppCompatTheme
Greeting()
}
}
}
}
@Composable
private fun Greeting() {
Text(
text = stringResource(R.string.greeting),
style = MaterialTheme.typography.h5,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = dimensionResource(R.dimen.margin_small))
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
3. 在Activity/Fragment...中使用Compopse
可參考新建compose應用內的實作方式,直接使用setContent方法,
五、最后
好記性不如爛筆頭,初識 Jetpack Compose 系列是我自己的學習筆記,在加深知識鞏固的同時,也可以鍛煉一下寫作技能,文章中的內容僅作參考,如有問題請留言指正,
為了方便大家更好的學習Kotlin,我特地將下面的檔案整合到Github中,希望能幫助到感興趣的讀者,
專案地址:Github


轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/297331.html
標籤:其他
