android compose混合开发 fragment中使用compose

Posted android超级兵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android compose混合开发 fragment中使用compose相关的知识,希望对你有一定的参考价值。

环境:

  • 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配置地址


原创不易,您的点赞就是对我最大的支持!

以上是关于android compose混合开发 fragment中使用compose的主要内容,如果未能解决你的问题,请参考以下文章

Android混合开发该怎么搞

androd H5混合开发 当无网络下,android怎么加载H5界面

Google开源,Android Jetpack Compose最新开发应用指南

Android GNSS开发前置知识——Android基础开发

Android GNSS开发前置知识——Android基础开发

Android GNSS开发前置知识——Android基础开发