Last active
March 8, 2025 08:34
-
-
Save pflammertsma/83b30c893555fa23e006408b8b3dce75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2024 Google LLC. | |
// SPDX-License-Identifier: Apache-2.0 | |
@OptIn(ExperimentalFoundationApi::class) | |
@Composable | |
fun PositionFocusedItemInLazyLayout( | |
parentFraction: Float = 0.3f, | |
childFraction: Float = 0f, | |
content: @Composable () -> Unit, | |
) { | |
// This bring-into-view spec pivots around the center of the scrollable container | |
val bringIntoViewSpec = remember(parentFraction, childFraction) { | |
object : BringIntoViewSpec { | |
override fun calculateScrollDistance( | |
// Initial position of item requesting focus | |
offset: Float, | |
// Size of item requesting focus | |
size: Float, | |
// Size of the lazy container | |
containerSize: Float | |
): Float { | |
val childSmallerThanParent = size <= containerSize | |
val initialTargetForLeadingEdge = | |
parentFraction * containerSize - (childFraction * size) | |
val spaceAvailableToShowItem = containerSize - initialTargetForLeadingEdge | |
val targetForLeadingEdge = | |
if (childSmallerThanParent && spaceAvailableToShowItem < size) { | |
containerSize - size | |
} else { | |
initialTargetForLeadingEdge | |
} | |
return offset - targetForLeadingEdge | |
} | |
} | |
} | |
// LocalBringIntoViewSpec will apply to all scrollables in the hierarchy | |
CompositionLocalProvider( | |
LocalBringIntoViewSpec provides bringIntoViewSpec, | |
content = content, | |
) | |
} | |
// To implement, provide a LazyRow as the PositionFocusedItemInLazyLayout's content | |
PositionFocusedItemInLazyLayout(parentFraction = 0.5f) { | |
LazyRow {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Dawid, is
@OptIn(ExperimentalFoundationApi::class)
causes any performance issue ?