android compose混合开发 fragment中使用compose

本文介绍如何将Android项目升级到Jetpack Compose,并详细说明了所需的Gradle插件版本、配置步骤及常见依赖项。同时提供了在Fragment中使用Compose的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境:

  • system: macOS
  • android studio: 4.2
  • gradle:7.0.3
  • distributionUrl:7.1.1-bin
  • jdk:11
  • kotlin_version:1.4.23

注意:compose是基于kotlin的,所以kotlin的环境就不过多介绍了…

将项目升级为7.0+

# build.gradle

buildscript {
	ext {
        compose_version = '1.0.0'
    }
	dependencies {
        classpath "com.android.tools.build:gradle:7.0.0"
        // classpath 'com.android.tools.build:gradle:4.1.3'
	}
}

gradle插件也需要升级为7.0+

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
# distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip

在对应的app模块中开启compose

android {
	defaultConfig{...}

	// 启用 JetPack Compose
    buildFeatures {
        compose = true
    }
    
	// 设置kotlin和java虚拟机保持一致
	// java
	compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    // kotlin
    kotlinOptions {
        jvmTarget = "1.8"
    }
	# composea选项 compose_version = 1.0.0
	composeOptions {
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.5.10'
    }
	
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

添加一些compose常用依赖

implementation 'androidx.core:core-ktx:1.3.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-preview:$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"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

注意,appcompat版本必须>1.3 否则会提示:

Jetpack Compose: java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from DecorView

原因:工程的 appcompat 版本太低,找不到ViewTreeLifecycleOwner扩展方法

implementation 'androidx.appcompat:appcompat:1.3.0'

详情参考地址

这样基本配置信息就完成啦

在fragment中使用compose

class MyFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
                MyTest()
            }
        }
    }

    @Composable
    fun MyTest() {
        Text(text = "hello compose")
    }
}

ok,大功告成!

另外一种写法 dialog

class MyDialogFragment : DialogFragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.dialog_demo_compose, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val container: ComposeView = view.findViewById(R.id.compose_in_android_view)
        container.setContent {
            DemoDialogCompose()
        }
    }
}

@Composable
@Preview
fun DemoDialogCompose() {
    val context = LocalContext.current
    Column(
        modifier = Modifier
            .background(color = Color.White)
            .padding(start = 16.dp, end = 16.dp),
        verticalArrangement = Arrangement.SpaceEvenly,
        horizontalAlignment = Alignment.Start
    ) {
        Text(
            text = "这是一个弹框",
            fontSize = 20.sp,
            color = Color(
                ContextCompat.getColor(context, android.R.color.holo_blue_light)
            )
        )
        Text(
            text = "这是compose的一个弹框",
            fontSize = 16.sp,
            color = Color(
                ContextCompat.getColor(context, android.R.color.darker_gray)
            )
        )
    }
}

dialog_demo_compose.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:background="@android:color/black">

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_in_android_view"
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</FrameLayout>

如何使用:

class MyFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            setContent {
//                MyTest()
                MyDialogFragment().show(childFragmentManager,"tag")
            }
        }
    }
    @Composable
    fun MyTest() {
        Text(text = "hello compose")
    }
}

来看看效果:


注意:版本一定要对应,否则有意想不到的问题..

官方compose配置地址


原创不易,您的点赞就是对我最大的支持!
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

s10g

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值