0

I am trying a Tic tac toe sample project. Once user performs click I am receiving callbacks but when trying to update text it's not basically updating text. Below is my code, please help. So far I have tried Need to put below text to shut-up SO error bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla:

enum class Player { Human, Computer } var board = arrayListOf("", "", "", "", "", "", "", "", "") private var currentPlayer = Player.Computer fun updatePosition(position: Int) { if (board[position].isEmpty()) if (currentPlayer == Player.Human) { board[position] = "X" currentPlayer = Player.Computer } else { board[position] = "O" currentPlayer = Player.Human } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ComposeTicTacToeTheme { Surface( modifier = Modifier.fillMaxWidth(), color = MaterialTheme.colors.background ) { Greeting(board, this::updatePosition) } } } } 
@Composable fun Greeting(board: ArrayList<String>, onclick: (Int) -> Unit) { Column{ Row { Cell(board[0]) { onclick(0) } Cell(board[1]) { onclick(1) } Cell(board[2]) { onclick(2) } } Row { Cell(board[3]) { onclick(3) } Cell(board[4]) { onclick(4) } Cell(board[5]) { onclick(5) } } Row { Cell(board[6]) { onclick(6) } Cell(board[7]) { onclick(7) } Cell(board[8]) { onclick(8) } } } } @Composable fun Cell( name: String, onClick: () -> Unit ) { Card( modifier = Modifier .width(130.dp) .height(130.dp) .padding(12.dp), elevation = 8.dp, contentColor = Color.Black, shape = RoundedCornerShape(80.dp), onClick = onClick ) { Text( name, fontSize = 80.sp, textAlign = TextAlign.Center, modifier = Modifier .background(color = Color.Yellow) ) } } 

1 Answer 1

1

In order to let Compose know that recomposition is needed, you have to use a special State wrapper for your values. In case of array, you can use mutableStateListOf instead of arrayListOf:

val board = mutableStateListOf("", "", "", "", "", "", "", "", "") 

For more details I suggest you start with state in Compose documentation, including this youtube video which explains the basic principles.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.