Android Kotlin: How to set EditText min length

Android Kotlin - Enforcing Minimum Characters in Edit Text

This code demonstrates how to restrict the minimum number of characters allowed for user input in an EditText field within an Android application written in Kotlin. It achieves this functionality by creating a custom extension function for the EditText class.

The code is divided into three parts:

  1. MainActivity.kt: This file defines the main activity class responsible for handling the user interface and logic. It retrieves the EditText reference from the layout and applies the filterMinLength extension function with the desired minimum character length.

  2. Extension Functions: The code defines three extension functions:

    • filterMinLength(min: Int): This function attaches three listeners to the EditText:
      • onFocusChangeListener: Checks the text length when the EditText loses focus.
      • setOnEditorActionListener: Checks the text length when the user presses the "Done" button on the keyboard.
      • setOnKeyListener: Checks the text length when the user presses the Enter key.
    • setLengthError(min: Int): This function checks the current text length against the minimum requirement. If it's below the minimum, it sets an error message on the EditText and hides the soft keyboard. Otherwise, it hides the keyboard and displays a toast message with the submitted text.
    • hideSoftKeyboard(editText: EditText): This function hides the soft keyboard programmatically using the system's InputMethodManager service.
  3. activity_main.xml: This file defines the layout of the activity. It contains a single EditText element with the desired properties.

Summary

This code provides a user-friendly way to enforce a minimum character length on an EditText field. It checks the length at various points during user interaction and provides informative feedback through error messages and toast notifications. Additionally, it demonstrates the use of extension functions to extend the functionality of existing classes.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.Toast


class MainActivity : Activity() {
    private lateinit var editText:EditText

    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)

        // apply edit text filter minimum characters length
        editText.filterMinLength(6)
    }
}


// extension function to filter edit text minimum characters length
fun EditText.filterMinLength(min: Int){
    // check minimum length on focus change
    onFocusChangeListener = View.OnFocusChangeListener { view, b ->
        if (!b) { setLengthError(min) }
    }

    // check minimum length on keyboard done click
    setOnEditorActionListener { v, actionId, event ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            setLengthError(min)
        }
        false
    }

    // check minimum length on enter key press
    setOnKeyListener { p0, p1, p2 ->
        if (p2.action == KeyEvent.ACTION_DOWN &&
            p1 == KeyEvent.KEYCODE_ENTER) {
            setLengthError(min)
            true
        } else {
            false
        }
    }
}


// extension function to check edit text minimum length of characters
fun EditText.setLengthError(min: Int){
    error = try {
        val value = text.toString().trim()
        if (value.length < min){
            "minimum length $min characters."
        }else{
            // hide soft keyboard
            context.hideSoftKeyboard(this)

            Toast.makeText(context,"You submitted : $value",
                Toast.LENGTH_SHORT).show()
            null
        }
    }catch (e: Exception){
        "minimum length $min characters."
    }
}


// extension function to hide soft keyboard programmatically
fun Context.hideSoftKeyboard(editText: EditText){
    (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).apply {
        hideSoftInputFromWindow(editText.windowToken, 0)
    }
}
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:inputType="text|textVisiblePassword"
        android:padding="12dp"
        android:textSize="30sp"
        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" />

</androidx.constraintlayout.widget.ConstraintLayout>
android kotlin - EditText min length android kotlin - Set EditText min length
More android kotlin tutorials