Last active
July 17, 2024 11:59
-
-
Save kenkoro/a5e77fb139dbfd86f09fb2d59bef71f7 to your computer and use it in GitHub Desktop.
Pull-to-refresh gesture support
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
package com.kenkoro.ui.pull.to.refresh | |
import ... | |
@OptIn(ExperimentalMaterial3Api::class) | |
@Composable | |
fun <T> PullToRefreshLazyColumn( | |
modifier: Modifier = Modifier, | |
items: List<T>, | |
content: @Composable (T) -> Unit, | |
isRefreshing: Boolean, | |
onRefresh: () -> Unit, | |
lazyListState: LazyListState = rememberLazyListState(), | |
) { | |
val pullToRefreshState = rememberPullToRefreshState() | |
Box(modifier = modifier.nestedScroll(pullToRefreshState.nestedScrollConnection)) { | |
LazyColumn( | |
modifier = Modifier.fillMaxSize(), | |
state = lazyListState, | |
contentPadding = PaddingValues(8.dp), | |
verticalArrangement = Arrangement.spacedBy(8.dp), | |
) { | |
items(items) { | |
content(it) | |
} | |
} | |
if (pullToRefreshState.isRefreshing) { | |
LaunchedEffect(Unit) { | |
onRefresh() | |
} | |
} | |
LaunchedEffect(isRefreshing) { | |
if (isRefreshing) { | |
pullToRefreshState.startRefresh() | |
} else { | |
pullToRefreshState.endRefresh() | |
} | |
} | |
PullToRefreshContainer( | |
modifier = Modifier | |
.align(Alignment.TopCenter) | |
.offset(y = (-30).dp), | |
state = pullToRefreshState, | |
) | |
} | |
} | |
/* NOTE: imports | |
import androidx.compose.foundation.layout.Arrangement | |
import androidx.compose.foundation.layout.Box | |
import androidx.compose.foundation.layout.PaddingValues | |
import androidx.compose.foundation.layout.fillMaxSize | |
import androidx.compose.foundation.layout.offset | |
import androidx.compose.foundation.lazy.LazyColumn | |
import androidx.compose.foundation.lazy.LazyListState | |
import androidx.compose.foundation.lazy.items | |
import androidx.compose.foundation.lazy.rememberLazyListState | |
import androidx.compose.material3.ExperimentalMaterial3Api | |
import androidx.compose.material3.pulltorefresh.PullToRefreshContainer | |
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState | |
import androidx.compose.runtime.Composable | |
import androidx.compose.runtime.LaunchedEffect | |
import androidx.compose.ui.Alignment | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.input.nestedscroll.nestedScroll | |
import androidx.compose.ui.unit.dp | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment