---
# System prepended metadata

title: 'Jetpack Compose - Part-1 : 開發環境'
tags: [Android, compose, kotlin]

---

# Jetpack Compose - Part-1 : 開發環境


---

## Jetpack Compose 是用來創建原生Android UI的tool kit
* 取代UI介面的大量xml file，改用composable函數來組合UI

* 目前只能使用Preview版本
* 下載Canary
https://developer.android.com/studio/preview

### 建立專案
![](https://i.imgur.com/E3EcEoT.png)

* 跟原本的Android Studio介面差異不大
* 但res底下已經沒有layout了
![](https://i.imgur.com/0VcHrSk.png)
* onCreate區塊，setContent取代了setContentView()
    ```kotlin=
        class MainActivity : ComponentActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                FirstComposeTheme {
                    // A surface container using the 'background' color from the theme
                    Surface(color = MaterialTheme.colors.background) {
                        Greeting("Android")
                    }
                }
            }
        }
    }
    ```
    
* gradle也有一些不同
    * minSdk從21開始
    * compose true這個未來在正式版或許可以兼容現有專案去做整合升級
```kotlin=
plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.firstcompose"
        minSdk 21
        targetSdk 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.4.32'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.0-alpha06'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}
```

###### tags: `compose` `kotlin` `Android`