I have a composable that gets a 5 digits value on a string, but i need to send it as an int, i have tried the .toInt()
but it seems that is not working for some reason, this is my code
@Composable
fun ParentConfirmScreen(
onConfirm: (Int) -> Unit,
registerUiState: RegisterScreenUiState,
navigateTo: (String) -> Unit,
goBack: () -> Unit,
) {
var pinValue by remember { mutableStateOf("")}
PinView(pinText = pinValue ,
onValueChange ={pinValue = it},
type = PIN_VIEW_TYPE_BORDER )
SecondaryButton(
text = "Continuar",
modifier = Modifier
.padding(8.dp)
.testTag(PARENT_PROFILE_BTN_TEST_TAG),
enabled = true
) {
onConfirm (pinValue.toInt())
}
}
}
}
}
const val PIN_VIEW_TYPE_UNDERLINE = 0
const val PIN_VIEW_TYPE_BORDER = 1
@Composable
fun PinView(
pinText: String,
onValueChange:(String)-> Unit,
digitColor: Color = MaterialTheme.colors.primary,
digitSize: TextUnit = 30.sp,
containerSize: Dp = digitSize.value.dp * 2,
digitCount: Int = 5,
type: Int = PIN_VIEW_TYPE_UNDERLINE,
) {
Column(verticalArrangement = Arrangement.Center) {
BasicTextField(
value = pinText,
onValueChange = { onValueChange(it) },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
decorationBox = {
Row(horizontalArrangement = Arrangement.SpaceBetween) {
repeat(digitCount) { index ->
DigitView(index, pinText, digitColor, digitSize, containerSize, type = type)
}
}
}
)
}
}
@Composable
private fun DigitView(
index: Int,
pinText: String,
digitColor: Color,
digitSize: TextUnit,
containerSize: Dp,
type: Int = PIN_VIEW_TYPE_UNDERLINE,
) {
val modifier = if (type == PIN_VIEW_TYPE_BORDER) {
Modifier
.width(containerSize)
.padding(bottom = 3.dp)
} else Modifier.width(containerSize)
Column(horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center) {
Text(
text = if (index >= pinText.length) "" else pinText[index].toString(),
color = digitColor,
modifier = modifier,
style = MaterialTheme.typography.body1,
fontSize = digitSize,
textAlign = TextAlign.Center)
if (type == PIN_VIEW_TYPE_BORDER) {
Spacer(modifier = Modifier.height(2.dp))
Divider(
Modifier
.width(50.dp)
.padding(bottom = 2.dp, top = 5.dp)
.offset(y = -10.dp),
color = MaterialTheme.colors.primary,
thickness = 1.dp)
}
}
}
any idea how to fix this?
CodePudding user response:
I stripped things down and I'm still not sure what is "not working" but calling
pinValue.toInt()
converts a number String representation to an Int value.
Your ParentConfirmScreen
composable (removed unnecessary codes)
@Composable
fun ParentConfirmScreen(
onConfirm: (Int) -> Unit
) {
var pinValue by remember { mutableStateOf("")}
Button(
onClick = {
onConfirm(pinValue.toInt())
}
){}
}
and its usage outside
setContent {
ParentConfirmScreen(
onConfirm = { pinAsInteger ->
// its already an integer here, and you can perform number operations on it
Log.e("LogTag", "${pinAsInteger * 10 / 2 % 200}")
}
)
}