// InToCm Example // Input a length in inches value in the TextField // then output the length in centimeters whenever // the textfield value changes. // Output NaN for illegal input. package it372.ssmith.intocm import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import java.util.Locale class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { MainLayout( ) } } } @Composable fun MainLayout( ) { var valueInch = remember { mutableStateOf("0")} var valueCm = remember { mutableStateOf("0")} Column(modifier = Modifier .padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally) { // Textfield contains a length in inches. TextField(value = valueInch.value, label = { Text("Enter a Length in Inches:") }, onValueChange = { valueInch.value = it valueCm.value = "NaN" valueInch.value.toDoubleOrNull( )?.let { valueCm.value = String.format("%.2f", it * 2.54) } }, modifier = Modifier .padding(bottom = 50.dp, top = 50.dp, start = 20.dp, end = 20.dp) .size(width = 200.dp, height = 75.dp) .fillMaxWidth( ), textStyle = TextStyle.Default.copy(fontSize = 28.sp) ) // Text element contains length in centimeters Text(text = valueCm.value, modifier = Modifier .padding(bottom = 50.dp, top = 50.dp, start = 20.dp, end = 20.dp) .size(width = 200.dp, height = 50.dp) .background(Color(0xFFE0E0FF)) .fillMaxWidth( ), fontSize = 25.sp, textAlign = TextAlign.Center ) } } @Preview(showBackground = true) @Composable fun GreetingPreview() { MainLayout( ) }