Vivek Modi
Vivek Modi

Reputation: 7151

Background selector not working in jetpack compose

Hello I am using lazycolumn inside column to show my nested list. When I am trying to click on single item, it's clicking on whole another items as well instead of single and color is not changing as well.

 binding.itemComposable.setContent {
     val interactionSource = remember { MutableInteractionSource() }
     val isPressed by interactionSource.collectIsPressedAsState()
     val backgroundColor = if (isPressed) DuckEggBlue else OffWhite
     val clickable = Modifier.clickable(
         interactionSource = interactionSource,
         indication = LocalIndication.current
     ) {
         println("Item Click")
     }
     Column(
         modifier = Modifier
             .fillMaxSize(),
         verticalArrangement = Arrangement.spacedBy(12.dp)
     ) {
         val options = getOptions()
         options.forEachIndexed { _, optionText ->
             Card(
                 shape = RoundedCornerShape(4.dp),
                 modifier = Modifier.then(clickable)
             ) {
                 Text(
                     modifier = Modifier
                         .fillMaxWidth()
                         .background(backgroundColor)
                         .padding(16.dp),
                     text = optionText,
                     style = Typography.h3,
                     fontWeight = FontWeight.Medium,
                     color = Slate
                 )
             }
         }
     }
 }

You can check in the video

  1. All items are selecting instead of single

  2. When selecting item background color is not changing according to my DuckEggBlue color.

Thanks

Upvotes: 0

Views: 802

Answers (1)

beyondtheteal
beyondtheteal

Reputation: 858

Since the state of isPressed is outside of your .forEachIndexed loop, the single instance of the state is shared between every row. If you would like each row to have its own instance state, simply move that block into the loop.

enter image description here

Upvotes: 1

Related Questions