HOW DID WE ENCOUNTER THE COMPOSE KEYPAD CHALLENGE?
While working on a tablet-based healthcare scheduling platform, we encountered a highly specific UI requirement: a custom numeric keypad for logging clinician rounding times. The standard Android OS keyboard was too cluttered for rapid data entry, so the design called for an in-app keypad specifically tailored for a 12-hour time format.
The goal was simple on the surface. When a nurse typed “5”, the UI should display “5:00”. Typing “53” should display “5:30” and “1130” should format to “11:30”. Crucially, invalid inputs needed to be rejected seamlessly. If the current input was “5”, pressing “7” (which would result in an invalid “5:70”) should be ignored, leaving the state at “5”.
During the initial implementation using Jetpack Compose’s state-based BasicTextField API, we realized that handling custom keypad inputs programmatically introduced unexpected state synchronization issues. Our custom keypad edits were bypassing standard Compose input pipelines, allowing invalid times to slip into the core state. This challenge inspired this deep-dive into standardizing input and output transformations so other teams can avoid similar pitfalls when managing complex state in Compose.
WHAT WAS THE BUSINESS CONTEXT AND SYSTEM ARCHITECTURE?
The application acts as a critical data entry point for hospital staff. Speed and accuracy are paramount. Because this data synchronizes in real-time with an enterprise backend, we could not afford to send malformed timestamps. The source of truth for the input had to remain strictly numeric (raw digits), while the user-facing display handled the localized formatting.
In our Compose architecture, we utilized the modern TextFieldState API alongside BasicTextField. This API introduces InputTransformation for mutating or rejecting text before it commits to the state and OutputTransformation for modifying how the text is rendered on screen without altering the underlying raw data.
The architectural requirement dictated a strict separation of concerns:
- The
TextFieldStatemust contain only valid raw digits. - The
OutputTransformationmust strictly format the raw digits into a 12-hour time string. - The validation logic must enforce valid time domains (hours 1-12, minutes 0-59) as a single source of truth.
WHAT WENT WRONG WITH PROGRAMMATIC STATE EDITS?
The standard Compose BasicTextField pipeline works perfectly when users type on a hardware or software system keyboard. The keystrokes pass through the InputTransformation, which validates and accepts or rejects the proposed change.
However, a custom in-app keypad does not rely on the OS Input Method Editor (IME). Instead, it modifies the TextFieldState programmatically. Initially, our engineers implemented keypad logic like this:
state.edit {
append(digit)
}
Because programmatic changes to TextFieldState do not automatically trigger the InputTransformation attached to the BasicTextField, invalid inputs like “57” were appended directly to the state. The custom keypad was effectively creating a backdoor around our validation logic.
To patch this, the team attempted to manually apply the transformation immediately after the edit:
state.edit {
append(digit)
with(timeInputTransformation) {
transformInput()
}
}
While this prevented the invalid state from persisting, it coupled the custom keypad deeply to the internals of the text field transformation layer. It felt like a hack. We needed an idiomatic way to ensure the domain logic was respected uniformly, regardless of whether the input came from a physical keyboard, a paste action or our custom UI keypad.
HOW DID WE EVALUATE POTENTIAL ARCHITECTURAL SOLUTIONS?
To establish a clean, maintainable architecture, we analyzed several approaches to enforce validation.
DID WE CONSIDER A VIEWMODEL-ONLY STATE APPROACH?
We initially considered moving all state management and validation into the ViewModel, completely abandoning Compose’s TextFieldState. Every button press would fire an intent to the ViewModel, which would calculate the new string, validate it and push down a new UI state. While this guarantees a single source of truth, it introduces a slight recomposition latency on rapid typing and it moves text-selection and cursor-position management away from the UI layer where it belongs.
WHAT ABOUT USING VISUALTRANSFORMATION EXCLUSIVELY?
Earlier versions of Compose relied heavily on VisualTransformation. We explored using this to mask invalid inputs. However, masking does not prevent the underlying state from becoming corrupted. If a user typed “570”, the state would hold “570”, even if the UI showed an error. This violated our requirement that invalid times never remain in the state.
SHOULD WE MANUALLY INVOKE TRANSFORMATIONS ON EVERY KEYSTROKE?
The manual invocation of transformInput() inside the edit block worked functionally. However, structurally, InputTransformation is designed to be an adapter between the system IME and the Compose state. Forcing a custom UI component to trigger IME-level transformations obscures the actual domain logic. We concluded that validation logic needed to live outside the InputTransformation so it could be shared.
HOW DID WE IMPLEMENT THE FINAL CUSTOM KEYPAD VALIDATION?
The idiomatic solution was to extract the time-parsing logic into an independent, pure domain function. This allowed us to reuse the exact same validation rules in both the InputTransformation (for external inputs like hardware keyboards) and the custom keypad (for programmatic inputs).
1. The Core Domain Validator
We built a pure Kotlin extension function that acts as the single source of truth for validating a time string.
private const val MaxTimeDigits = 4
private const val MinuteDigits = 2
private val HourRange = 1..12
private val MinuteRange = 0..59
private data class TwelveHourTime(val hour: Int, val minute: Int)
private fun String.asTwelveHourTime(): TwelveHourTime? {
if (isEmpty() || length > MaxTimeDigits || !all(Char::isDigit)) return null
val hourLength = (length - MinuteDigits).coerceAtLeast(1)
val hour = take(hourLength).toInt()
val minute = drop(hourLength).padEnd(MinuteDigits, '0').toInt()
return if (hour in HourRange && minute in MinuteRange) {
TwelveHourTime(hour, minute)
} else {
null
}
}
private fun isValidTimeEntry(text: String): Boolean {
return text.isEmpty() || text.asTwelveHourTime() != null
}
2. The Input and Output Transformations
We kept the Transformations lightweight, delegating validation to our domain function.
private val timeInputTransformation = InputTransformation.byValue { current, proposed ->
if (isValidTimeEntry(proposed.toString())) proposed else current
}
private val timeOutputTransformation = OutputTransformation {
val time = asCharSequence().toString().asTwelveHourTime()
if (time != null) {
replace(0, length, "${time.hour}:${time.minute.toString().padStart(2, '0')}")
}
}
3. The Smart Custom Keypad
Instead of manually invoking transformInput() after mutating the state, the custom keypad now pre-validates the proposed change. If the resulting string is invalid, the edit is never applied to the state.
@Composable
fun TimeField() {
val state = rememberTextFieldState()
BasicTextField(
state = state,
readOnly = true, // Prevents system keyboard popup
inputTransformation = timeInputTransformation, // Handles external copy/paste
outputTransformation = timeOutputTransformation,
)
// Custom Keypad Button Example
Button(
onClick = {
val proposed = state.text.toString() + "5"
if (isValidTimeEntry(proposed)) {
state.edit { append("5") }
}
}
) {
Text("5")
}
// Backspace Button
Button(
onClick = {
state.edit {
if (length > 0) delete(length - 1, length)
}
}
) {
Text("Backspace")
}
}
By decoupling the validation logic, we achieved a clean, idiomatic architecture. The TextFieldState never holds invalid data, the UI is perfectly formatted and the custom keypad behaves predictably.
WHAT ARE THE KEY LESSONS FOR ENGINEERING TEAMS?
When solving state synchronization issues in modern UI toolkits, keeping concerns strictly separated is essential. For teams looking to scale their mobile architecture, consider these actionable insights:
- Decouple Domain Logic from UI Adapters: Never trap your validation rules inside an
InputTransformation. Extract them into pure functions that can be tested independently and invoked from multiple UI controllers. - Understand Programmatic vs. IME Edits:
TextFieldState.editoperates underneath the standard transformation pipeline. If you mutate state programmatically, you are responsible for validating that mutation beforehand. - OutputTransformation is Strictly Visual: Rely on
OutputTransformationsolely for display logic. It should never alter the actual data payload that gets sent to your database or API. - Pre-validate Custom Controls: When building custom keypads or dials, calculate the proposed state string in memory and run it through your validation logic before committing the change to the Compose state.
- Protect Against Edge Cases: Even if your custom keypad is the primary input method, always attach an
InputTransformationto theBasicTextFieldto safeguard against hardware keyboards, accessibility tools or clipboard paste actions.
This level of architectural rigor is what companies expect when they hire software developer teams to build mission-critical software. A deep understanding of these APIs prevents fragile UI code from making it into production.
HOW CAN YOU APPLY THIS TO YOUR NEXT MOBILE APPLICATION?
Handling custom input constraints in Jetpack Compose requires a strong grasp of how state flows between the raw data layer and the visual representation layer. By treating your text state as a single source of truth, isolating your domain validation and correctly applying transformations, you can build highly resilient custom user interfaces that never drop out of sync.
If you plan to hire android developers for mobile engineering or need to scale your team with architects who understand the nuances of modern declarative UI frameworks, contact us. We provide pre-vetted, dedicated engineering teams capable of delivering robust, enterprise-grade applications.
Social Hashtags
#JetpackCompose #AndroidDevelopment #Kotlin #AndroidDev #MobileAppDevelopment #ComposeUI #KotlinDevelopment #InputValidation #SoftwareArchitecture #CleanArchitecture #CustomKeypad #TextFieldState #MobileEngineering #AndroidDevelopers #SoftwareEngineering
Frequently Asked Questions
No. They serve different purposes. InputTransformation dictates what data is allowed into the TextFieldState (modifying or rejecting keystrokes). The newer OutputTransformation (which heavily overlaps with the older VisualTransformation) dictates how that valid data is rendered on the screen without changing the underlying state.
While you can inject validation logic via a ViewModel, it is generally recommended to keep keystroke-level transformations close to the UI layer to avoid recomposition latency. The domain logic (the parser) can be shared, but the execution of the transformation should remain tied to the Compose state holder.
In many enterprise applications, particularly healthcare, point-of-sale and logistics, speed is critical. Validating on submit causes friction. Immediate, keystroke-level validation via custom keypads reduces data entry errors and improves user efficiency.
InputTransformation is specifically designed as a filter for external input streams (like the system keyboard). TextFieldState.edit is a low-level programmatic API meant for developers to directly mutate state. By design, direct developer mutations assume the developer has already validated the input.
When you bypass the OS keyboard, you must manually ensure that your custom keypad buttons have appropriate semantic labels (e.g., contentDescription) so that screen readers can accurately announce the button actions and the updated text field state.
Success Stories That Inspire
See how our team takes complex business challenges and turns them into powerful, scalable digital solutions. From custom software and web applications to automation, integrations, and cloud-ready systems, each project reflects our commitment to innovation, performance, and long-term value.

Accelerated Healthcare Operations Automation with a Dedicated Offshore Development Team

Recruitment Operations Automation with Offshore Software Dev Team



















