Build an Android login screen with validation
A reliable Android login screen does more than checking whether two boxes contain text. It should explain mistakes quickly, work with autofill and password managers, and keep sensitive credentials out of logs and ordinary preference files. Good validation improves the sign-in experience, while the backend remains responsible for authenticating the account.
Build this as an Empty Views Activity called LoginActivity, with View Binding and Material Components. Start with an email field, password field, sign-in button, and progress indicator. Keep the layout responsive, expose errors to assistive technology, and define the behaviour before, during, and after the network request.
| Validation concern | During input | On submit | Backend |
|---|---|---|---|
| Empty field | Optionally mark as incomplete | Show a required-field error | Reject missing input |
| Email shape | Give gentle formatting guidance | Show a format error | Parse and normalise the address |
| Password | Never reveal stored credentials | Require a non-empty value | Verify the secret and account status |
| Duplicate request | Ignore repeated presses | Disable the button while loading | Apply rate limits and lockouts |
Set the project flow before drawing the form
Create an Empty Views Activity, name it LoginActivity, enable View Binding, and add the current stable Material Components library. Put the interface in activity_login.xml and place business logic in LoginActivity.kt or a small AuthRepository. This keeps the screen testable and prevents network code from being mixed into input handling.
Sketch three states: idle, submitting, and completed or failed. While idle, accept input. While submitting, disable duplicate presses, show progress, and preserve entered values. Afterwards, either open the authenticated area or keep the user on the form with a useful message. A forgotten-password action should lead to a separate recovery flow.
Define which checks are convenience checks and which are security checks. An email shape or empty field can be checked locally for fast feedback, but password validity, account status, lockouts, and authentication must come from the server. Treat client-side validation as a usability layer rather than a security boundary.
Create accessible input fields
Use TextInputLayout with TextInputEditText children so floating labels, password visibility controls, and field-level errors share one consistent pattern. A basic outlined layout can begin like this:
<com.google.android.material.textfield.TextInputLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:id="@+id/emailLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email_hint"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/emailInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autofillHints="emailAddress"
android:inputType="textEmailAddress"
android:imeOptions="actionNext" />
</com.google.android.material.textfield.TextInputLayout>
TextInputLayout owns the error property, placing the message below the input for TalkBack. Keep hints in string resources, set the keyboard type for email, and set autofillHints to emailAddress. For the password, use textPassword, apply a sensible maximum input length, and enable the password-toggle end icon.
If the product also accepts a phone number, an Australian account may need the +61 country prefix. A legacy country selector can be explored in Android Spinner Styles, although an exposed dropdown is often clearer on current Android versions. Test the selector with TalkBack, keyboard navigation, and large font settings rather than treating it as decoration.
Give the sign-in button an explicit action label, keep the progress indicator beside the action, and describe loading changes with live-region semantics. Do not rely on red borders or colour alone: each invalid field needs visible text. Ensure the focused field scrolls into view, and avoid hiding errors behind the keyboard or a narrow progress overlay.
Validate fields with Kotlin
Run field checks in Kotlin when the button is pressed, then clear and reapply errors in one place. The following example checks required values and a basic email format without deciding whether an account exists.
private fun validateForm(): Boolean {
val email = binding.emailInput.text?.toString()?.trim().orEmpty()
val password = binding.passwordInput.text?.toString().orEmpty()
var firstInvalid: View? = null
binding.emailLayout.error = null
binding.passwordLayout.error = null
if (email.isBlank()) {
binding.emailLayout.error = getString(R.string.error_email_required)
firstInvalid = binding.emailInput
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailLayout.error = getString(R.string.error_email_format)
firstInvalid = binding.emailInput
}
if (password.isEmpty()) {
binding.passwordLayout.error = getString(R.string.error_password_required)
if (firstInvalid == null) firstInvalid = binding.passwordInput
}
firstInvalid?.requestFocus()
return firstInvalid == null
}
Patterns.EMAIL_ADDRESS provides a quick client-side format check, but the server should parse and normalise the submitted address. Avoid complicated regular expressions that reject valid addresses. Password validation should normally require a non-empty value; minimum-length rules belong to account creation because existing users may have older passwords.
After validation passes, pass the trimmed email and untouched password to the repository. Never trim a password, because surrounding spaces can be meaningful. Clear the password only after a successful sign-in or an explicit reset, and never include either credential in analytics events, exception messages, or Logcat output.
Handle the request and session safely
Perform the authentication request over HTTPS with lifecycleScope, disable the button while it is active, and show a short progress state. Set a reasonable timeout and distinguish a connectivity failure from an invalid credential response. On success, start the authenticated destination; on failure, keep the form available for another attempt.
Return generic credential errors such as “Email or password is incorrect” so the endpoint does not reveal which accounts exist. Follow the server's retry guidance for rate limits and temporary lockouts, and offer a recovery route that does not disclose account existence. Multi-factor authentication can follow acceptance of the password.
Do not store the raw password in SharedPreferences, a database, or saved instance state. If the backend returns a refresh token, protect it with an Android Keystore-backed design, define an expiry, and remove it on sign-out. SharedPreferences remains suitable for non-sensitive interface choices such as the last selected sign-in method, but not for a password or bearer token without suitable encryption.
Test for Australian use and compliance
Test across the Android versions and screen sizes common in Australia, including Samsung devices and Google Pixels used in Sydney, Melbourne, Brisbane, and Perth. Run automated checks for empty fields, malformed email addresses, valid credentials, invalid credentials, slow responses, and rotation. Pair these with manual TalkBack, keyboard, and 200% font-scale checks.
Everyday Australian use makes network handling especially important. Commuters open apps on trains and trams, shop over mobile data, and may reconnect through café Wi-Fi after passing through a tunnel. The screen should time out cleanly, retain the email address, avoid replaying a request automatically, and explain that a connection is required without implying that the password was wrong.
The local market includes Australian banking, retail, transport, and fintech apps, so the flow should fit established Android patterns and expectations around biometric unlock and password autofill. If the operator is covered by the Privacy Act 1988, document handling under the Australian Privacy Principles and avoid collecting unnecessary personal details. Review privacy and terms disclosures for clarity under the Australian Consumer Law, and test consent choices without blocking basic account features unless consent is genuinely required.
A successful implementation combines immediate form feedback with server-side authentication, accessible errors, careful token handling, and realistic network testing. These choices produce a login flow that remains usable across Australian cities and mobile conditions while keeping credential decisions under the control of the backend.