android kotlin - EditText allow only certain characters

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:

  1. MainActivity.kt:

    • The code defines an Activity class named MainActivity.
    • 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.
  2. 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 the filter method.
    • The filter method iterates through the user's input and checks if each character exists in the accepted 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.
  3. 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 - EditText allow only certain characters
More android kotlin tutorials