classMainActivity : ComponentActivity() { overridefunonCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { UnitConverterTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { UnitConverter() } } } } }
@Composable funUnitConverter() {
var inputValue by remember{ mutableStateOf("1") } var outputValue by remember{ mutableStateOf("1") } var inputUnit by remember{ mutableStateOf("Meters") } var outputUnit by remember{ mutableStateOf("Meters") } // DropdownMenu(left input) should be expanded or not expanded var iExpanded by remember{ mutableStateOf(false) } var oExpanded by remember{ mutableStateOf(false) } // 100cm * 0.01 = 1m val iConversionFactor = remember{ mutableStateOf(1.0) } val oConversionFactor = remember{ mutableStateOf(1.0) }
funconverUnits() { // elvis operator: if value is null or not a number -> 0.0 else value.toDouble() val inputValueDouble = inputValue.toDoubleOrNull() ?: 0.0 val result = inputValueDouble * iConversionFactor.value / oConversionFactor.value outputValue = result.toString() }
Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text("Unit Converter", style = MaterialTheme.typography.headlineLarge) Spacer(modifier = Modifier.height(16.dp)) OutlinedTextField( value = inputValue, onValueChange = { // it means whatever you type on the TextField inputValue = it converUnits() }, // description label = { Text(text = "Enter Value")}) Spacer(modifier = Modifier.height(16.dp))