Home > Software design >  Displaying a check mark after click on Row component in compose
Displaying a check mark after click on Row component in compose

Time:03-10

I want to display a check mark/tick icon after clicking on Row component. There should be only one item marked - others are unmarked. Here is my code:

@Composable
fun ItemRow(viewModel: itemViewModel, item: Item) {

    item.name?.let {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .clickable { / *** / }
                .padding(16.dp)
        ) {
            Icon( / *** / )
            Text(
                text = it,
                / *** /
            )
        }
    }
}

I have tried something like this, but it changes nothing:

@Composable
fun ItemRow(viewModel: itemViewModel, item: Item) {
    var selectedId = ""
    item.name?.let {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .clickable {
                    selectedId = item.id
                }
                .padding(16.dp)
        ) {
            if (selectedId == item.id) {
                Icon( / *** / )
            }
            Text( /***/ )
        }
    }
}

CodePudding user response:

When you click on each row to show tick icon you have to update your model, for example:

data class UiState(val showTickIcon: Boolean = false)
@Composable
fun ItemRow(viewModel: itemViewModel, item: Item) {
    var selectedId = ""
    item.name?.let {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .clickable {
                    viewModel.updateState(true)
                }
                .padding(16.dp)
        ) {
            if (selectedId == item.id) {
                Icon( / *** / )
            }
            Text( /***/ )
        }
    }
}

in view model update your state flow

fun updateState(val isTick: Boolean) {
    _uiState.update {
        it.copy(showTickIcon = isTick)
    }
}

when your model updated and state changed, your compose function recompose and UI will update.

  • Related