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


原创不易,您的点赞就是对我最大的支持!
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
使用ComposeAndroidX完成相机预览,您可以按照以下步骤进行操作: 1. 首先,请确保您的项目已经启用了Compose和CameraX依赖项。您可以在build.gradle文件添加以下依赖项: ```kotlin // 添加Compose依赖 implementation 'androidx.compose.ui:ui:1.0.0' implementation 'androidx.compose.material:material:1.0.0' implementation 'androidx.compose.ui:ui-tooling-preview:1.0.0' implementation 'androidx.compose.runtime:runtime:1.0.0' // 添加CameraX依赖 def camerax_version = "1.1.0-alpha08" implementation "androidx.camera:camera-camera2:$camerax_version" implementation "androidx.camera:camera-lifecycle:$camerax_version" implementation "androidx.camera:camera-view:1.0.0-alpha29" ``` 2. 创建一个Compose布局文件,用于显示相机预览。例如,您可以创建一个名为CameraPreview.kt的文件,并编写以下代码: ```kotlin @Composable fun CameraPreview() { val lifecycleOwner = LocalLifecycleOwner.current AndroidView( modifier = Modifier.fillMaxSize(), factory = { context -> val previewView = PreviewView(context) val cameraProviderFuture = ProcessCameraProvider.getInstance(context) cameraProviderFuture.addListener({ val cameraProvider = cameraProviderFuture.get() val preview = Preview.Builder() .build() .also { it.setSurfaceProvider(previewView.surfaceProvider) } val cameraSelector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build() try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview) } catch (exception: Exception) { Log.e("CameraPreview", "Error starting camera preview: ${exception.message}") } }, ContextCompat.getMainExecutor(context)) previewView } ) } ``` 3. 在您的Compose Activity或Fragment使用`setContent`函数将CameraPreview添加到界面。例如: ```kotlin class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { CameraPreview() } } } ``` 这样,您就可以使用ComposeAndroidX完成相机预览了。请注意,这只是一个简单的示例,您可能需要根据您的应用程序需求进行更多的自定义和错误处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

s10g

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

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

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

打赏作者

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

抵扣说明:

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

余额充值