Skip to content

Instantly share code, notes, and snippets.

View Ahmad-Hamwi's full-sized avatar
🎯
Focusing

Ahmad Hamwi Ahmad-Hamwi

🎯
Focusing
View GitHub Profile
operator fun component2(): (Int) -> Unit = {
...
coroutineScope.launch {
if (smoothScroll) {
lazyListState.animateScrollToItem(syncedIndices[selectedTabIndex])
} else {
lazyListState.scrollToItem(syncedIndices[selectedTabIndex])
}
}
fun LazyListState.findFirstFullyVisibleItemIndex(): Int = findFullyVisibleItemIndex(false)
fun LazyListState.findLastFullyVisibleItemIndex(): Int = findFullyVisibleItemIndex(true)
fun LazyListState.findFullyVisibleItemIndex(reversed: Boolean): Int {
layoutInfo.visibleItemsInfo
.run { if (reversed) reversed() else this }
.forEach { itemInfo ->
val itemStartOffset = itemInfo.offset
val itemEndOffset = itemInfo.offset + itemInfo.size
@Composable
fun lazyListTabSync(...): TabSyncState {
...
LaunchedEffect(lazyListState) {
snapshotFlow { lazyListState.layoutInfo }.collect {
var itemPosition = lazyListState.findFirstFullyVisibleItemIndex()
if (itemPosition == -1) {
itemPosition = lazyListState.firstVisibleItemIndex
@Composable
fun TabSyncComposeScreen(categories: List<Category>) {
val (selectedTabIndex, setSelectedTabIndex, lazyListState) = tabSyncMediator(
mutableListOf(0, 2, 4), //Mandatory. The indices of lazy list items to sync the tabs with
tabsCount = 3, //Optional. To check for viability of the synchronization with the tabs. Optimal when equals the count of syncedIndices.
lazyListState = rememberLazyListState(), //Optional. To provide your own LazyListState. Defaults to rememberLazyListState().
smoothScroll = true, // Optional. To make the auto scroll smooth or not when clicking tabs. Defaults to true
)
@Composable
fun TabSyncComposeScreen(categories: List<Category>) {
val (selectedTabIndex, setSelectedTabIndex, lazyListState) = lazyListTabSync(categories.indices.toList())
Column {
MyTabBar(
categories = categories,
selectedTabIndex = selectedTabIndex,
onTabClicked = { index, _ -> setSelectedTabIndex(index) }
)
dependencies {
implementation 'io.github.ahmad-hamwi:tabsync-compose:1.0.0'
}
@Composable
fun TabSyncExampleScreen(categories: List<Category>) {
val selectedTabIndex by remember { mutableStateOf(0) }
val lazyListState = rememberLazyListState()
Column {
MyTabBar(
categories = categories,
selectedTabIndex = selectedTabIndex,
@Composable
fun MyLazyList(
categories: List<Category>,
listState: LazyListState = rememberLazyListState(),
) {
LazyColumn(
state = listState,
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
itemsIndexed(categories) { _, category ->
@Composable
fun MyTabBar(
categories: List<Category>,
selectedTabIndex: Int,
onTabClicked: (index: Int, category: Category) -> Unit
) {
ScrollableTabRow(
selectedTabIndex = selectedTabIndex,
edgePadding = 0.dp
) {
dependencies {
implementation 'io.github.ahmad-hamwi:tabsync:1.0.1'
}