androidkotlinandroid-jetpack-composeandroid-jetpack-compose-layoutandroid-jetpack-compose-row

Align row item in jetpack compose


I want to make row like this

Expected Output

enter image description here

AND

enter image description here

I tried this piece of code

DividerWithItem

@Composable
fun DividerWithItem(
    modifier: Modifier = Modifier,
    index: () -> Int,
    itemName: String,
    lastIndex: () -> Int,
    moreRowContent: @Composable RowScope.() -> Unit,
) {
    Column {
        if (index() == 0) {
            Divider(color = Cloudy, thickness = dimensionResource(R.dimen.separator_height_width))
        }
        Row(
            modifier = modifier,
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = itemName,
                modifier = Modifier.padding(vertical = 12.dp),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            moreRowContent()
        }
        if (index() <= lastIndex()) {
            Divider(color = Cloudy, thickness = 1.dp)
        }
    }
}

BpmOptionsLabel

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LazyItemScope.BpmOptionsLabel(
    index: () -> Int,
    optionName: String,
    lastIndex: () -> Int
) {
    DividerWithItem(
        modifier = Modifier
            .fillMaxSize()
            .animateItemPlacement(),
        index = index,
        itemName = optionName,
        lastIndex = lastIndex
    ) {
        Image(
            modifier = Modifier.weight(.3f),
            painter = painterResource(R.drawable.ic_menu),
            contentDescription = null,
        )
    }
}

BpmOptionsLabelPreview

@Preview(showBackground = true)
@Composable
fun BpmOptionsLabelPreview() {
    LazyColumn {
        item {
            BpmOptionsLabel(
                index = { 0 },
                "Item item item item item m 1",
                lastIndex = { 1 }
            )
        }
    }
}

Actual Output

enter image description here

Only problem is Text and Image item is not in proper place


Solution

  • In the DividerWithItem apply the weight(1f) to the Text

    Text(
        text = itemName,
        modifier = Modifier.padding(vertical = 12.dp).weight(1f),
        maxLines = 1,
        overflow = TextOverflow.Ellipsis
    )
    moreRowContent()
    

    and in the LazyItemScope.BpmOptionsLabel remove the weight modifier from the Image:

    Image(
        //modifier = Modifier.weight(.3f),
        painter = painterResource(R.drawable.ic_menu_gallery),
        contentDescription = null
    )
        
    

    enter image description here

    If you want to increase the space occupied by the Image, use a padding modifier:

    Image(
        //...
        modifier = Modifier.padding(horizontal = 20.dp)
    )
    

    enter image description here