TextFiled 演示輸入數(shù)字轉(zhuǎn)換金額
mutableState 使用
remember 委托記住輸入
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingCardTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
TipTimeScreen()
}
}
}
}
}
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun DefaultPreview() {
GreetingCardTheme {
// BirthdayGreetingWithImage(message = "Happy Birthdy David", from = " - Weimiao")
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
TipTimeScreen()
}
}
}
@Composable
fun TipTimeScreen() {
var amountInput by remember {
mutableStateOf("")
}
val amount = amountInput.toDoubleOrNull() ?: 0.0
val tip = calculateTIp(amount)
Column(
modifier = Modifier.padding(32.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = stringResource(id = R.string.calculate_tip),
fontSize = 24.sp,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
Spacer(modifier = Modifier.height(16.dp))
EditNumberField(value = amountInput, onValueChange = {amountInput = it})
Spacer(Modifier.height(24.dp))
Text(
text = stringResource(R.string.tip_amount, tip),
modifier = Modifier.align(Alignment.CenterHorizontally),
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
@Composable
fun EditNumberField(value: String, onValueChange: (String) -> Unit) {
TextField(
value = value,
onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(),
label = { Text(text = stringResource(id = R.string.cost_of_service)) },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
}
private fun calculateTIp(amount: Double, tipPercent: Double = 15.0):String {
val tip = tipPercent / 100 * amount
return NumberFormat.getCurrencyInstance().format(tip)
}
}