kotlin
@Composable
fun MyComponent(
displayString: String
) {
Text(displayString)
}
@Composable
fun MyComponent(
displayString: String
) {
Text(displayString)
}
@Composable
fun ConditionalComponent(condition: Boolean) {
if (condition) {
Text("Condition is true")
} else {
Text("Condition is false")
}
}
// Usage
ConditionalComponent(condition = true)
@Composable
fun Parent(data: String) {
IntermediateComponent(data = data)
}
@Composable
fun IntermediateComponent(data: String) {
ChildComponent(data = data)
}
@Composable
fun ChildComponent(data: String) {
Text("Received data: $data")
}
// Usage
Parent(data = "Some data")
@Composable
fun ClickableComponent() {
var clicked by remember { mutableStateOf(false) }
Button(onClick = { clicked = true }) {
Text(if (clicked) "Button clicked" else "Click me")
}
}
@Composable
fun TextInputComponent() {
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = { newText -> text = newText },
label = { Text("Enter text") }
)
}
@Composable
fun ExampleComponent() {
Text("Hello, World!")
}
@Preview(showBackground = true)
@Composable
fun ExampleComponentPreview() {
ExampleComponent()
}
Additionally, you can also use Showkase, an open source library by Airbnb that allows you to view themes preview functions in an auto-generated component browser that can be viewed on an Android device.
@Composable
fun ListComponent(items: List<String>) {
LazyColumn {
items(items) { item ->
Text(item)
}
}
}
// Usage
val items = listOf("Item 1", "Item 2", "Item 3")
ListComponent(items = items)
data class Person(val name: String, val age: Int, val id: String)
@Composable
fun ItemKeysExample(items: List<Person>) {
LazyColumn {
items(items, key = { person -> person.id }) { person ->
Text("Name: ${person.name}, Age: ${person.age}")
}
}
}
@Composable
fun Parent(
header: @Composable () -> Unit,
content: @Composable () -> Unit
) {
Column {
header()
content()
}
}
// Usage
Parent(
header = { Text("Header") },
content = { Child() }
)
@Composable
fun Child() {
Text("Child Content")
}
@Composable
fun ModifiersExample() {
Text(
"Hello, World!",
modifier = Modifier
.padding(16.dp)
.background(Color.Blue)
)
}
@Composable
fun Counter() {
var count by remember { mutableStateOf(0) }
Button(onClick = { count = count + 1 }) {
Text("Count: $count")
}
}
val CustomLocal = compositionLocalOf<String> { "Default data" }
@Composable
fun Parent(data: String) {
CompositionLocalProvider(CustomLocal provides data) {
Intermediate()
}
}
@Composable
fun Intermediate() {
Child()
}
@Composable
fun Child() {
val data = CustomLocal.current
Text("Received data: $data")
}
// Usage
Parent(data = "Some data")
@Composable
fun SideEffectOnLoadComponent() {
LaunchedEffect(Unit) {
// Perform side effect, e.g. fetch data, update external data source
}
// Other UI components
Text("Hello, World!")
}