Now that you can see what you’re typing in the chat input text box, it’s time to do something with that text when you hit the Send button.
In Conversation.kt, update the onClick() method for the button in SimpleUserInput() so that the Button code now looks like this:
Button(onClick = {
chatOutputText = chatInputText
chatInputText = ""
}) {
Text(text = stringResource(id = R.string.send_button))
}
This does two things when you click the button:
-
First, it updates the value of
chatOutputTextwith the text that you typed into the text box. - Secondly, it clears out whatever was in the text box.
Build and run. Type something into the chat input text box, and then tap the Send button.
Whatever you type now appears in the UI above the text box.
Cool, now the Send button is actually doing something! But it’s not quite what you want, is it? The text is just above the text box and not really part of the list of chat messages. Furthermore, if you type something else and hit Send again, whatever you type just replaces the previous thing you typed instead of updating the list of chat messages.
In the top-level composable, replace SimpleUserInput() with:
UserInput(onMessageSent = { content ->
uiState.addMessage(
content, null
)
})
Command-click on addMessage (Control-click in Windows) to jump into the definition of this function, which is defined in ConversationUiState.kt:
fun addMessage(msg: String, photoUri: Uri?) {
// TODO : implement :]
}
Update this function as follows:
fun addMessage(msg: String, photoUri: Uri?) {
val message = Message(text = msg)
val messageModel = MessageUiModel(message = message, user = meUser)
_messages.add(messageModel) // Add to the beginning of the list
}
You’ll need to define meUser, so add a new variable after _messages:
private val meUser = User(id = "me", firstName = "Khaled", lastName = "Abdul Wahab")
You can replace the first and last name with your own name.
Build and run. Type something into the text box and hit the Send button. Type in a few messages and hit Send each time.
Now, your messages get added to the list of chat messages!