Below is an image of what we will be working on in this post.
Binary TextField Composable
Below is the code snippet for the binary text field.
@Composable fun BinaryTextField( value: String, decimalValue: String, errorMessage: String? = null, imeAction: ImeAction = ImeAction.Default, onValueChange: (String) -> Unit ) { val isError: Boolean = errorMessage != null Column(modifier = Modifier.fillMaxWidth()) { OutlinedTextField( modifier = Modifier.fillMaxWidth(), value = value, isError = isError, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = imeAction ), onValueChange = { value -> val input = value.filter { it == '0' || it == '1' } onValueChange(input) }, label = { Text("Binary") } ) Box( modifier = Modifier .padding(start = 16.dp, end = 12.dp) ) { if (isError) { if (errorMessage != null) { Text( errorMessage, style = TextStyle( color = MaterialTheme.colorScheme.error, fontSize = 12.sp ) ) } } else { Text(text = "In decimal $decimalValue") } } } }
The simplest way to accept binary values is to have the TextField’s keyboardType to KeyboardType.Number and ultimately, filter out digits that are not 1s or 0s from the input.
To convert the binary value into decimal here is a function
fun convertBinaryToDecimal(binary: String): Double { var num = binary.toLong() var decimalNumber = 0.0 var i = 0 var remainder: Long while (num.toInt() != 0) { remainder = num % 10 num /= 10 decimalNumber += (remainder * 2.0.pow(i.toDouble())) ++i } return decimalNumber }
Complete Source Code
Here is the full source code.
const val format = "#,###" @OptIn(ExperimentalMaterial3Api::class) @Composable fun ExampleScreen() { var binary by remember { mutableStateOf("") } Scaffold( topBar = { TopAppBar( title = { Text(text = "Binary TextField Example") }, ) } ) { padding -> Box(Modifier.padding(padding)) { Column( modifier = Modifier .padding(16.dp) .fillMaxSize(), ) { BinaryTextField( value = binary, decimalValue = convertBinaryToDecimal(binary), errorMessage = null, imeAction = ImeAction.Done ) { binary = it } } } } } fun convertBinaryToDecimal(binary: String): String { if (binary.isBlank()) return "" var num = binary.toLong() var decimalNumber = 0.0 var i = 0 var remainder: Long while (num.toInt() != 0) { remainder = num % 10 num /= 10 decimalNumber += (remainder * 2.0.pow(i.toDouble())) ++i } val df = DecimalFormat(format) return df.format(decimalNumber) }