Transcript
Replace the entire contents of MainActivity.kt with the following:
package com.kodeco.chat
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column {
var chatInputText by remember { mutableStateOf("Type your text here") }
var chatOutputText by remember { mutableStateOf("Press Send to update this text")}
Text(text = chatOutputText)
OutlinedTextField(
value = chatInputText,
onValueChange = {
chatInputText = it
},
label = { Text("Label") }
)
Button(onClick = {
chatOutputText = chatInputText
chatInputText = ""
}) {
Text(text = "Send")
}
}
}
}
}
Note: Sometimes, when using new objects in your classes, Android Studio won’t recognize them until you import the class definition. Android Studio shows this by highlighting the object in red.
To import the class definition:
• macOS: Click the object and press Option-Return.
• Windows: Click the object and press Alt-Enter.
You can also choose to let Android Studio handle imports automatically for you when pasting code. Select Android Studio ▸ Settings ▸ Editor ▸ General ▸ Auto Import. In the Kotlin section, check the Add unambiguous imports on the fly box. Click Apply in the bottom-right.
Going through the code:
-
Column
places a column in the view. A column is a layout group that stacks all of its contents, or its “children”, in a vertical column. You’ll learn all about different view layout groups later. -
chatInputText
andchatOutputText
, and give them some default values. Note the use ofby remember
. The remember API is used by Composable functions to store an object in memory and update it during recomposition.
You define two variables, -
Text
composable to display the contents of a chat message.
You define a simple -
OutlinedTextField
is a styled text field designed to accept user input from the keyboard. -
Button
which, when tapped, updates the text area with what you type into the text field.
Finally, you define a
That’s it! Run your app. Enter some text into the text field and hit the Send button. You’ll see the text at the top update with whatever you typed.
Congratulations! You’ve just created the most basic chat app, one that can accept input and display it back on screen.