user3450498
user3450498

Reputation: 267

Trying to set maxLength in EditText, but characters can still go beyond max

I'm trying to set a max length of 2 in an EditText so that users cannot type in more than 2 characters for abbreviations. But when running the code, I can still type in any amount of characters I want. Is there something wrong with the way I implemented maxLength?

<EditText
                    android:id="@+id/register_edit_stcn"
                    android:maxLength="2"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:background="#00000000"
                    android:capitalize="sentences"
                    android:gravity="left"
                    android:hint="ST OR CN"
                    android:inputType="text"
                    android:letterSpacing="0.095"
                    android:textAllCaps="true"
                    android:textColor="#FFF"
                    android:textSize="16dp" />

Upvotes: 1

Views: 713

Answers (2)

Shahzad Afridi
Shahzad Afridi

Reputation: 2158

I have tested this code and It worked. You can't type more than 3 characters because of maxLength=3

    EditText message = (EditText) findViewById(R.id.register_edit_stcn);
    int maxLength = 3;
    message.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});

Upvotes: 1

Red M
Red M

Reputation: 2799

When you add an InputFilter object manually, the xml property is overridden, so it will reset the maxLength to its default value.

is there a way to limit character limit while still having InputFilter?

You can try this:

Create a custom inputFilter class:

package com.test;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) { }     
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

register_edit_stcn.setFilters(new InputFilter[]{new InputFilterMinMax("0", "2"), new InputFilter.LengthFilter(2)});

Credit to this solution by @Pratik Sharma

Upvotes: 2

Related Questions