Skip to content

Commit

Permalink
Adds section on using Haze in deep UI hierarchies. (#494)
Browse files Browse the repository at this point in the history
  • Loading branch information
StylingAndroid authored Jan 27, 2025
1 parent 266c281 commit ed1f0a9
Showing 1 changed file with 85 additions and 0 deletions.
85 changes: 85 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,91 @@ Box {
)
}
```
## Deep UI hierarchies

You can pass `HazeState` objects to composables as arguments. For example:

```kotlin hl_lines="3 7 11"
@Composable
fun HazeExample(modifier: Modifier = Modifier) {
val hazeState = remember { HazeState() }

Box(modifier = modifier) {
Background(
hazeState = hazeState,
modifier = Modifier.fillMaxSize()
)
Foreground(
hazeState = hazeState,
modifier = Modifier.fillMaxSize()
)
}
}
```

You can then use the argument to configure `hazeSource` and `hazeEffect`:

```kotlin hl_lines="4 13-16"
@OptIn(ExperimentalHazeMaterialsApi::class)
@Composable
fun Foreground(
hazeState: HazeState,
modifier: Modifier = Modifier
) {
Box(modifier = modifier) {
Text(
text = stringResource(R.string.haze_text),
modifier = modifier
.align(Alignment.Center)
.wrapContentSize()
.hazeEffect(
state = hazeState,
style = HazeMaterials.ultraThin()
)
)
}
}
```

However, this can problematic in deep hierarchies when you need to pass the `HazeState` instances
down through many levels. To avoid this you can use a composition local to pass the `HazeState`
down to the descendants in the hierarchy:

```kotlin hl_lines="1 5 7 12 20 28"
val LocalHazeState = compositionLocalOf { HazeState() }

@Composable
fun HazeExample(modifier: Modifier = Modifier) {
val hazeState = remember { HazeState() }

CompositionLocalProvider(LocalHazeState provides hazeState) {
Box(modifier = modifier) {
Background(modifier = Modifier.fillMaxSize())
Foreground(modifier = Modifier.fillMaxSize())
}
}
}
.
.
.
@OptIn(ExperimentalHazeMaterialsApi::class)
@Composable
fun Foreground(modifier: Modifier = Modifier) {
val hazeState = LocalHazeState.current
Box(modifier = modifier) {
Text(
text = stringResource(R.string.haze_text),
modifier = modifier
.align(Alignment.Center)
.wrapContentSize()
.hazeEffect(
state = hazeState,
style = HazeMaterials.ultraThin()
)
)
}
}
```

## Styling

Expand Down

0 comments on commit ed1f0a9

Please sign in to comment.