Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal

Posted 安果移不动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal相关的知识,希望对你有一定的参考价值。

效果

还是通过隐式传参来修改一些样式

自定义MyCard.kt

package com.anguomob.jecpack.activity.compose.composition.local

import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.Card
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.graphics.Color

data class Elevations(val card: Dp = 0.dp)

val LocalElevations = compositionLocalOf 
    Elevations()


object CardElevation 
    val height: Elevations
        get() = Elevations(card = 10.dp)
    val low: Elevations
        get() = Elevations(card = 5.dp)


@Composable
fun MyCard(
    elevation: Dp = LocalElevations.current.card,
    backgroundColor: Color,
    content: @Composable () -> Unit
) 
    Card(
        elevation = elevation,
        modifier = Modifier.size(200.dp),
        backgroundColor = backgroundColor,
        content = content
    )

 使用

package com.anguomob.jecpack.activity.compose.composition.local

import androidx.compose.foundation.layout.Column
import androidx.compose.material.*
import androidx.compose.material.SnackbarDefaults.backgroundColor
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalContext
import com.anguomob.jecpack.R


@Composable
fun CompositionSample2() 
    Column() 
        CompositionLocalProvider(LocalElevations provides CardElevation.height) 
            MyCard(

                backgroundColor = MaterialTheme.colors.onSurface.copy(alpha = 0.05f)
            ) 

            

        
        MyCard(backgroundColor = MaterialTheme.colors.onSurface.copy(alpha = 0.05f)) 

        

    


对于初次学习还懵懂的CompositionLocal

现在已经非常的简单容易理解了

第一篇:

Kotlin Compose 隐式传参 CompositionLocalProvider_安果移不动的博客-CSDN博客

以上是关于Kotlin Compose 自定义 CompositionLocalProvider CompositionLocal的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin Compose 自定义布局 StaggeredGrid

Kotlin 元编程之 KSP 实战:通过自定义注解配置Compose导航路由

Kotlin 元编程之 KSP 实战:通过自定义注解配置Compose导航路由

Kotlin 写自定义 ViewGroup

Android Compose 中的哑重组

Kotlin Compose compositionLocalOf 与 staticCompositionLocalOf