https://kotlinlang.org logo
#compose
Title
# compose
n

nuhkoca

03/19/2022, 3:33 PM
Hello I have a setup below for different views based on different states. Views for
Success
and
Error
states already work as expected because they aren’t centered on the screen but
LoadingView
should be centered instead but it is always placed on top. How do I fix this? Thank you.
Copy code
...
Scaffold(topBar = topBar) {
    Box(
        modifier = Modifier
            .padding(it)
            .verticalScroll(rememberScrollState())
    ) {
        when (collectionState) {
            CollectionState.Loading -> LoadingView()
            is CollectionState.Success -> {
                ScreenView(
                    collection = collectionState.collection,
                    onWatchlistItemClick = onWatchlistItemClick,
                    onDisclaimerTextClicked = onDisclaimerTextClicked
                )
            }
            CollectionState.Error -> ErrorView(onTryAgainClicked = onTryAgainClicked)
        }
    }
}
...
Copy code
@Composable
private fun LoadingView() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        CircularProgressIndicator()
    }
}
Scoping my composable with
BoxScope
seems to be working but I am not sure if this is a good approach
Copy code
@Composable
private fun BoxScope.LoadingView() {
    Box(modifier = Modifier.align(Alignment.Center)) {
        CircularProgressIndicator()
    }
}
t

trashcoder

03/19/2022, 7:18 PM
hi, maybe the outer box should "fillMaxSize" as well?
Copy code
Box(
        modifier = Modifier
            .padding(it)
            .verticalScroll(rememberScrollState())
    ) {
a

Arsen

03/19/2022, 7:23 PM
Try this:
Copy code
Scaffold {
    BoxWithConstraints(
        contentAlignment = Alignment.Center,
        modifier = Modifier.fillMaxSize()
    ) {
        Text("w: $maxWidth \nh: $maxHeight")

        val size = if (maxWidth < maxHeight) {
            maxWidth / 2
        } else {
            maxHeight / 2
        }

        CircularProgressIndicator(modifier = Modifier.size(size))
    }
}
n

nuhkoca

03/19/2022, 9:40 PM
@Arsen thanks but there are another states(Error and Success) which shouldn’t be centered on the screen. That’s the reason I cannot pass
Alignment.Center
in the parent box.
@trashcoder thanks I forgot the post that part I did exactly the same 🙂
👍 1
a

Arsen

03/20/2022, 11:26 AM
Define separate BoxWithConstraints for each case (if/else or when)