Jetpack Compose: Basic components

In this article, we will discuss the basic components present in the Jetpack Compose.

Text

Text is the most basic view and is almost required by every component. Jetpack Compose makes it easier to display or write text.

@Composable
fun SimpleText() {
    Text(text = "Hello World!")
}

Buttons

A view with an onClick function. We can add other Composables as child elements of the Button.

@Preview(showBackground = true)
@Composable
fun DisplayButton() {
    Button(onClick = {
        Log.i("Button", "clicked")
    }, Modifier.padding(4.dp)) {
        Text(
            text = "Button")
    }
}

Textfield

It allows users to enter and modify text.

@Composable
fun DisplayTextField() {
    var name by remember {
        mutableStateOf("")
    }
    TextField(value = name, onValueChange = { it ->
        name = it
    }, label = { Text(text = "Username") })
}

Checkbox

A component that allows the user to select multiple options from a given list.

@Composable
fun DisplayCheckBox() {
    var checkStatus by remember {
        mutableStateOf(false)
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        Checkbox(checked = checkStatus, onCheckedChange = {
            checkStatus = it
        })
        Text(text = "Checkbox", Modifier.clickable { checkStatus = !checkStatus })
    }
}

RadioButton

A component that allows the user to select only one option from a given list.

@Preview(showBackground = true)
@Composable
fun DisplayRadioButton() {
    val sports = listOf("Cricket", "Tennis", "Basketball")
    val (selected, onOptionSelected) = remember {
        mutableStateOf(sports[0])
    }
    Column(Modifier.padding(4.dp), verticalArrangement = Arrangement.Center) {
        sports.forEach { text ->
            Row(modifier = Modifier.padding(4.dp), verticalAlignment = Alignment.CenterVertically) {
                RadioButton(selected = selected == text, onClick = {
                    onOptionSelected(text)
                })
                Text(text = text, Modifier.clickable { onOptionSelected(text) })
            }
        }
    }
}

Conclusion

In this article, we have discussed only a few UI basic components which are the building blocks for making an interface. We will be discussing some more components in the upcoming blogs.  

Stay tuned for the updates.

Daksh
Hey, I Am Daksh Bhardwaj, A Tech Enthusiast , My Core Interests Lies In Hybrid App Development And Web Development Using Latest Tools And Techniques. Improving every day!