EditText length Filter - Android User Interface

Android examples for User Interface:EditText

Description

EditText length Filter

Demo Code


//package com.java2s;

import android.support.annotation.NonNull;

import android.text.InputFilter;

import android.text.Spanned;

import android.widget.EditText;

public class Main {

    public static void lengthFilter(final EditText editText,
            final int length) {
        InputFilter[] filters = new InputFilter[1];

        filters[0] = new InputFilter.LengthFilter(length) {
            public CharSequence filter(@NonNull CharSequence source,
                    int start, int end, @NonNull Spanned dest, int dstart,
                    int dend) {
                if (dest.toString().length() >= length) {
                    return "";
                }//w  ww .  j  a va2  s. c om
                return source;
            }
        };
        // Sets the list of input filters that will be used if the buffer is Editable. Has no effect otherwise.
        editText.setFilters(filters);
    }
}

Related Tutorials