Home > front end >  Change alignment of child in column in jetpack compose
Change alignment of child in column in jetpack compose

Time:11-24

I want to change the horizontalAlignment of particular child and remaining will use the same horizontalAlignment. Is this possible in Column?

For example, Column parent modifier use horizontalAlignment = Alignment.CenterHorizontally, and I want particular child modifier will be different horizontalAlignment.

        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxSize()
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            ScreenImage()
            Description()
            if (viewModel.isBluetoothEnabled) {
                ScanDeviceList(scanDeviceList)
            } else {
                Warning()
                Spacer(modifier = Modifier.weight(1f))
                TryAgainButtonView { tryAgainAction() }
                ButtonView { openSettingAction() }
            }
        }

I want to change ScanDeviceList() to be different horizontalAlignment

@Composable
fun ColumnScope.ScanDeviceList(scanDeviceList: List<ScanResult>) {
    Spacer(modifier = Modifier.height(20.dp))
    AnimatedVisibility(scanDeviceList.isNotEmpty()) {
        Text(
            text = stringResource(R.string.vailable_device),
        )
    }
}

Many Thanks

CodePudding user response:

You can use Modifier.align(Alignment.Start) to align a particular child. So for example to make your ScanDeviceList() at the Start of the column the code will be like this:

@Composable
fun ColumnScope.ScanDeviceList(scanDeviceList: List<ScanResult>) {
    Spacer(modifier = Modifier.height(20.dp))
    AnimatedVisibility(
        scanDeviceList.isNotEmpty(),
        modifier = Modifier.align(Alignment.Start)
    ) {
        Text(
            text = stringResource(R.string.vailable_device),
        )
    }
}

You can also pass the modifier as an argument to ScanDeviceList composable function to make it more generic to the code will be like this:

@Composable
fun ColumnScope.ScanDeviceList(
    scanDeviceList: List<ScanResult>, 
    modifier: Modifier = Modifier
) {
    Spacer(modifier = Modifier.height(20.dp))
    AnimatedVisibility(
        scanDeviceList.isNotEmpty(), 
        modifier = modifier
    ) {
        Text(
            text = stringResource(R.string.vailable_device),
        )
    }
}

And when you call it you can specify the alignment that you want:

ScanDeviceList(scanDeviceList, modifier = Modifier.align(Alignment.Start))

Note: adding the modifier an argument to your composable functions is considered as a best practice because it will make the function reusable like the example above you can call ScanDeviceList with Alignment.Start or Alignment.End without changing the function itself, just by passing a different modifier as a parameter.

  • Related