【问题标题】:Add jetpack compose to existing project将 jetpack compose 添加到现有项目
【发布时间】:2020-08-16 22:31:43
【问题描述】:

我有一个现有的 android studio 项目,我想在我的项目中使用 jetpack compose。文档说明了如何使用 jetpack compose 创建新项目,但如何将其与现有项目一起使用?

【问题讨论】:

    标签: android android-layout kotlin android-jetpack-compose


    【解决方案1】:

    Jetpack compose 要求 minSdkVersion 至少为 21。因此在您的 app/build.gradle 文件中添加/更新以下内容

    android{ 
       //...
       defaultConfig {       
          minSdkVersion 21
          targetSdkVersion 29
          //...
       }
      //...
     }
    

    您还需要使用 Android studio(来自 canary 频道)才能使用最新功能的 jetpack-compose。

    现有项目的最简单方法

    第 1 步:

    在项目窗口中,right click on the package you want to include the compose activity -> compose -> Empty compose activity

    File -> new -> compose -> Empty compose activity.
    

    第 2 步

    将出现一个对话窗口。填写必填字段并点击Finish

    就是这样。


    现有项目的手动配置

    第 1 步:project/build.gradle 文件中使用最新版本的 kotlin 和 gradle 插件。

    例子:

    buildscript {
         ext {
        compose_version = '1.0.0-beta08'
    }
    
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:7.1.0-alpha02'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.10"
        }
    }
    
    allprojects {
        repositories {
            google()
            jcenter()
        }
    }
    

    在您的project/app/build.gradle 中,添加以下内容

    android{ 
       //...
       defaultConfig {       
          minSdkVersion 21
          targetSdkVersion 30
          //...
       }
      //...
    
      kotlinOptions {
           jvmTarget = "1.8"
            useIR = true
      }
    
      buildFeatures {
        compose true
      }
      composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.4.32'
    }
    }
    
    
    dependencies {
      implementation 'androidx.core:core-ktx:1.5.2'
    implementation 'androidx.appcompat:appcompat:1.3.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-beta1'
    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-test-junit4:$compose_version"
    }
    

    第 2 步: 将撰写活动添加到清单文件中。

     <application      
        android:label="@string/app_name"
         <!-- ... -->
         >
         <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.MyApp.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
          <!-- ... -->
      </application>
    

    第 3 步:

    创建 jetpack-compose Activity。

    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import androidx.compose.Composable
    import androidx.ui.foundation.Text
    import androidx.ui.core.setContent
    import androidx.ui.material.MaterialTheme
    import androidx.ui.tooling.preview.Preview
    
    class MainComposeActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                MaterialTheme {
                    Greeting("Android")
                }
            }
        }
    }
    
    @Composable
    fun Greeting(name: String) {
        Text(text = "Hello $name!")
    }
    
    @Preview
    @Composable
    fun DefaultPreview() {
        MaterialTheme {
            Greeting("Android")
        }
    }
    

    就是这样。快乐编码:)

    【讨论】:

      【解决方案2】:

      只需关注official setup。 添加你的build.gradle:

      plugins {
        id 'org.jetbrains.kotlin.android' version '1.4.0'
      }
      
      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"
              useIR = true
          }
      
          composeOptions {
              kotlinCompilerExtensionVersion "1.0.0-alpha01"
          }
      }
      
      dependencies {
          // You also need to include the following Compose toolkit dependencies.
          implementation 'androidx.compose.ui:ui:1.0.0-alpha01'
          implementation 'androidx.compose.material:material:1.0.0-alpha01'
          implementation 'androidx.ui:ui-tooling:1.0.0-alpha01'
          ...
      }
      

      同样从 1.0.0-alpha01 开始,您可以将 Compose 与您现有的 UI 设计相结合。

      在你的布局中添加ComposeView:

      <LinearLayout
          xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
        
          <TextView/>
      
          <androidx.compose.ui.platform.ComposeView
              android:id="@+id/compose_view"
              android:layout_width="match_parent"
              android:layout_height="match_parent" />
      
      </LinearLayout>
      

      在您的Activity 中,使用XML ID 设置ComposeView,并调用setContent() 以使用Compose:

      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main_std)
          .apply {
              findViewById<ComposeView>(R.id.compose_view).setContent {
                 MaterialTheme () {
                    Text(text = "Compose text", style = MaterialTheme.typography.body2)
                 }
               }
          }
      }
      

      【讨论】:

      • 您能否让旧的 XML 布局预览器在其中包含 ComposeViews 的 xml 文件中工作?在我的 android studio (4.2) 上,预览器因 IllegalStateException 而失败,因为 ComposeView 显然没有附加 ViewTreeLifecycleOwner。
      【解决方案3】:

      在你的root level build.gradle 里面添加 compose version 变量 buildscript

      ext {
          compose_version = '1.0.1'
      }
      

      现在在你的app level build.gradle 添加 buildFeatures 和 composeOptions 在你的 android { } 块内

      buildFeatures {
          compose true
      }
      composeOptions {
          kotlinCompilerExtensionVersion compose_version
      }
      

      在你的依赖中

      // Jetpack dependencies
      implementation "androidx.compose.ui:ui:$compose_version"
      implementation "androidx.compose.material:material:$compose_version"
      implementation 'androidx.activity:activity-compose:1.4.0'
      // Jetpack debug dependencies
      debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
      

      现在您可以开始在现有/新项目中使用 compose

      class MainActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContent {
              // your compose code goes here
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 2020-12-22
        • 2013-02-12
        • 1970-01-01
        相关资源
        最近更新 更多