Home > Blockchain >  Jetpack Compose - Access specific item in row/grid
Jetpack Compose - Access specific item in row/grid

Time:04-02

How can I change the composables within a row?

For example if I had something like this:

@Composable
fun WordGrid() {
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
        MyCard("")  basically a card with Text
        MyCard("")
        MyCard("")
    }
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
        MyCard("")
        MyCard("")
        MyCard("")
   
    }
}

fun MyCard(text: String?) {
Card() {
    Text(
        text = text?: ""
        )
    }
}

and two buttons:

Button "A" and Button "B"

each time a button is clicked a card should get the text from the button, and then the next card and then the last.

clicking buttons A B A B would give you:

@Composable
fun WordGrid() {
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
        MyCard("A")  basically a card with Text
        MyCard("B")
        MyCard("A")
    }
    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
        MyCard("B")
        MyCard("")
        MyCard("")
   
    }
}

How do you go about something like this unidirectionally? With XML you would be able to access the card.id directly from the ViewModel, here they have no id.

Is the only way to check if a button has been pressed and then create a state for that, pass this to the row and run through a for loop?

This seems much more complicated than having a simple id to grab.

CodePudding user response:

In Compose you can't access views by ID. The only way is to manipulate the state which is used to build it.

I suggest you start with this youtube video which explains the basic principles of when you need to use state in compose. You can continue deepening your knowledge with state in Compose documentation.

In your case you can create a mutable state list of strings, build your views based on this list and update it using the buttons by index.

Here's a basic example of what you're trying to do:

val cards = remember { List(6) { "" }.toMutableStateList() }
var editingIndex by remember { mutableStateOf(0) }
Column {
    Row {
        val editButton = @Composable { text: String ->
            Button({
                cards[editingIndex] = text
                editingIndex  = 1
            }) {
                Text(text)
            }
        }
        editButton("A")
        editButton("B")
    }
    cards.chunked(cards.count() / 2).forEach { rowCards ->
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
            rowCards.forEach {
                MyCard(it)
            }
        }
    }
}
  • Related