Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpackandroid-jetpack-compose-lazy-column

Change Alignment of particular child item in LazyColumn jetpack compose


I am using LazyColumn in my @Compsoable screen. Inside LazyColumn there are so many child and which align verticalArrangement = Arrangement.Top and horizontalAlignment = Alignment.CenterHorizontally. But in one child Item I want to use from Start. Can we do that?

        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            contentPadding = PaddingValues(16.dp),
            verticalArrangement = Arrangement.Top,
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {

            item {
                ommonContent()
            }

            item {
                HoldDescription()
            }

            item {
                WarningMessage()
            }

            item {
                Devices() // change this item from Start..
            }

            // more item in here
        }

Expected Output

enter image description here

I tried with these answer to Modifier.align(Alignment.Start) but it gives me error

@Composable
fun Devices(
    isEmpty: Boolean,
) {
    AnimatedVisibility(
        isEmpty,
        modifier = Modifier.align(Alignment.Start)
    ) {
        Text() 
    }
}

Error in Image

enter image description here


Solution

  • To apply the align modifier you can scope your composable with the required scope.
    You can use:

    @Composable
    fun ColumnScope.Devices(
        isEmpty: Boolean,
    ) {
        AnimatedVisibility(
            isEmpty,
            modifier = Modifier.fillMaxWidth().align(Alignment.Start)
        ) {
            Text("xxx")
        }
    }
    

    Otherwise you can use:

    @Composable
    fun Devices(
        modifier: Modifier,
        isEmpty: Boolean,
    ) {
        AnimatedVisibility(
            isEmpty,
            modifier = modifier
        ) {
            Text("xxx")
        }
    }
    

    and then

    item(){
    
       Column() {
            Devices(
                modifier = Modifier.fillMaxWidth().align(Alignment.Start),
                isEmpty = true)
        }
    }