Last active
September 5, 2024 11:57
-
-
Save pflammertsma/83b30c893555fa23e006408b8b3dce75 to your computer and use it in GitHub Desktop.
This file contains 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 = 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 {} | |
} |
@pflammertsma I used this snippet to document migration from TvLazyLists to LazyLists https://medium.com/@dejwidh/lazylist-pivotoffset-without-tvlazylist-7ad24fe439ab. I hope it's fine.
Hi Dawid, well observed; we are in the process of bringing scrollable containers back into componse-foundation and this code snippet replaces the pivotOffset
parameter.
I will have more to share once we are closer to updating the TV libraries.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Will that be added to tv-foundation once
TvLazyList
s are removed?