Home > database >  How to always center a progress bar in the center of a screen in Jetpack Compose?
How to always center a progress bar in the center of a screen in Jetpack Compose?

Time:01-19

I'm trying to paginate some items got from an API. I want to load 10 items at a time. What I need is to always display a progress in the center of the screen on top of everything. This what I have tried:

val items = viewModel.items.collectAsLazyPagingItems()
Box(
    modifier = Modifier.fillMaxSize()
) {
    LazyColumn {
        items(
            items = items
        ) { item ->
            ProductCard(
                item = item
            )
        }
        items.apply {
            when(loadState.refresh) {
                is Loading -> item { ProgressBar() }
                is Error -> //Log error
            }
        }
    }
}

Here is my ProgressBar:

@Composable
fun ProgressBar() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ){
        CircularProgressIndicator()
    }
}

The problem is that when I start the app, the progress bar starts loading on the top of the 10 loading items. Once I load more, it stays between the bottom of the existing items and the top of the new 10. How to have a progress bar always centered in the center of the screen, no matter how many pages I load?

CodePudding user response:

Try to place your ProgressBar outside of LazyColumn with proper alignment or use Modifier.align() in ProgressBar

val items = viewModel.items.collectAsLazyPagingItems()
Box(
    modifier = Modifier.fillMaxSize(),
    contentAlignment = Alignment.Center
) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(
            items = items
        ) { item ->
            ProductCard(
                item = item
            )
        }
    }
    when(loadState.refresh) {
                is Loading -> ProgressBar()
                is Error -> //Log error
    }
}
  •  Tags:  
  • Related