compose混合开发 fragment中使用compose

前言:今天心血来潮,把已有的项目升级成了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配置地址

 
————————————————
版权声明:本文为CSDN博主「s10g」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44819566/article/details/122460239

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在`MainActivity`更新`mutableStateOf`对象,您需要将其传递给`MainFragment`,然后在`MainFragment`更改其值。以下是一种可能的方法: 首先,在`MainActivity`创建一个`mutableStateOf`对象: ```kotlin class MainActivity : AppCompatActivity() { private val myMutableState = mutableStateOf("Initial Value") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyMainScreen(myMutableState) } } } ``` 然后,在`MainFragment`接收该对象并更新它: ```kotlin class MainFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val myMutableState = remember { mutableStateOf("Initial Value") } return ComposeView(requireContext()).apply { setContent { MyFragmentScreen(myMutableState) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Update the value of myMutableState from MainActivity (requireActivity() as MainActivity).myMutableState.value = "New Value" } } ``` 在`MainFragment`,我们首先使用`remember`关键字创建了一个`mutableStateOf`对象。然后,我们将其传递给了`MyFragmentScreen`,这是一个自定义的Compose函数,用于显示该状态的值。 在`onViewCreated`方法,我们从`MainActivity`获取了该对象,并直接更新了其值。这将自动通知Compose系统重新绘制UI以反映新的值。请注意,由于该对象是可变的,因此我们可以将其值更改为任何其他值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值