Android Kotlin - Restricting Characters in EditText
This code demonstrates how to restrict user input in an EditText to a specific set of characters in an Android application written in Kotlin. It achieves this functionality by creating a custom extension function for EditText and utilizing Android's built-in InputFilter mechanism.
Explanation:
MainActivity.kt:
- The code defines an
Activity
class namedMainActivity
. - It retrieves references to the EditText and TextView widgets from the layout using
findViewById
. - The
certainCharactersOnly
extension function is called on the EditText object, passing a String containing the allowed characters. - The TextView displays a message indicating the allowed characters.
- The code defines an
certainCharactersOnly Extension Function:
- This function takes a String
accepted
as an argument, representing the allowed characters. - It creates an
InputFilter
object. The filter logic is implemented within thefilter
method. - The
filter
method iterates through the user's input and checks if each character exists in theaccepted
string. - If an invalid character is found, a flag is set.
- A
StringBuilder
is used to build a new character sequence containing only valid characters. - Finally, the filter returns the modified character sequence (if valid characters exist) or null (if only invalid characters were entered).
- The EditText's
filters
property is set to an array containing this newly created filter, effectively restricting user input.
- This function takes a String
activity_main.xml:
- This file defines the layout for the activity using ConstraintLayout.
- It includes an EditText and a TextView.
Summary
This code provides a clean and reusable way to restrict user input in an EditText to a predefined set of characters. The extension function approach simplifies the code and promotes maintainability. The user is informed about the allowed characters through the TextView, enhancing the user experience.
MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.os.Bundle
import android.text.InputFilter
import android.widget.EditText
import android.widget.TextView
class MainActivity : Activity() {
private lateinit var editText:EditText
private lateinit var textView:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the widgets reference from XML layout
editText = findViewById(R.id.editText)
textView = findViewById(R.id.textView)
// allow certain characters only in edit text
val accepted = "abcABC012$*#"
editText.certainCharactersOnly(accepted)
// show accepted characters in text view
textView.text = "Accepted only '$accepted'"
}
}
// extension function to allow certain characters only in edit text
fun EditText.certainCharactersOnly(accepted:String){
val filter = InputFilter { source, start, end, dest, dstart, dend ->
var includesInvalidCharacter = false
val stringBuilder = StringBuilder()
val destLength = dend - dstart + 1
val adjustStart = source.length - destLength
for (i in start until end) {
val sourceChar = source[i]
if (
accepted.contains(sourceChar)
) {
if (i >= adjustStart) stringBuilder.append(sourceChar)
} else includesInvalidCharacter = true
}
if (includesInvalidCharacter) stringBuilder else null
}
filters = arrayOf(filter)
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="32dp">
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:padding="12dp"
android:textSize="30sp"
android:fontFamily="sans-serif-condensed-medium"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.12" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:fontFamily="sans-serif-condensed-medium"
android:gravity="center"
android:padding="8dp"
android:textColor="#483D8B"
android:textSize="26sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
- android kotlin - Show soft keyboard when EditText is focused
- android kotlin - EditText hide error
- android kotlin - Set EditText digits programmatically
- android kotlin - EditText allow only positive numbers
- android kotlin - Canvas draw point
- android kotlin - Canvas erase drawing
- android kotlin - Canvas draw text shadow
- android kotlin - Canvas draw line
- android kotlin - Canvas draw arc between two points
- android kotlin - Canvas draw path
- android kotlin - Canvas draw text rotate
- android kotlin - Canvas draw text with border
- android kotlin - Canvas draw text in rectangle
- android kotlin - Canvas draw text
- android kotlin - Canvas draw circle