Last active
December 3, 2023 18:07
-
-
Save alphadotwork/c0f1963ab92d8926640f4c405155a402 to your computer and use it in GitHub Desktop.
otp compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MainActivity : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
OtpComposeTheme { | |
val (pinValue,onPinValueChange) = remember{ | |
mutableStateOf("") | |
} | |
Surface(color = MaterialTheme.colors.background) { | |
PinView(pinText =pinValue , onPinTextChange = onPinValueChange, type = PIN_VIEW_TYPE_BORDER ) | |
} | |
} | |
} | |
} | |
} | |
const val PIN_VIEW_TYPE_UNDERLINE = 0 | |
const val PIN_VIEW_TYPE_BORDER = 1 | |
@Composable | |
fun PinView( | |
pinText: String, | |
onPinTextChange: (String) -> Unit, | |
digitColor: Color = MaterialTheme.colors.onBackground, | |
digitSize: TextUnit = 16.sp, | |
containerSize: Dp = digitSize.value.dp * 2, | |
digitCount: Int = 4, | |
type: Int = PIN_VIEW_TYPE_UNDERLINE, | |
) { | |
BasicTextField(value = pinText, | |
onValueChange = onPinTextChange, | |
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), | |
decorationBox = { | |
Row(horizontalArrangement = Arrangement.SpaceBetween) { | |
repeat(digitCount) { index -> | |
DigitView(index, pinText, digitColor, digitSize, containerSize, type = type) | |
Spacer(modifier = Modifier.width(5.dp)) | |
} | |
} | |
}) | |
} | |
@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) | |
.border( | |
width = 1.dp, | |
color = digitColor, | |
shape = MaterialTheme.shapes.medium | |
) | |
.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_UNDERLINE) { | |
Spacer(modifier = Modifier.height(2.dp)) | |
Box( | |
modifier = Modifier | |
.background(digitColor) | |
.height(1.dp) | |
.width(containerSize) | |
) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment