Strange behavior using maxLength on EditText



Maybe this is already answered but I can't find it on SO.


I have a very simple requirement: Restrict the length of characters in an EditText.


I use the maxLength tag in xml for this as follows:



<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="5"
android:hint="text"/>
</RelativeLayout>


The strange thing is, if the length of the inputted text exceeds the limit of 5, the text can't be deleted by pressing backspace. The inputted text remains in the EditText field. So, I added an InputFilter to have a look what happens. Here's the code:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.edit);

InputFilter filter = new InputFilter() {
private char[] restricted = {'{'};
@Override
public CharSequence filter(CharSequence source,
int start,
int end,
Spanned dest,
int dstart,
int dend) {

if (source != null) {
Log.v("edit","source = " + source.toString());
Log.v("edit","start = " + start);
Log.v("edit","end = " + end);
}
if (dest != null) {
Log.v("edit","dest= " + dest.toString());
Log.v("edit","dstart = " + dstart);
Log.v("edit","dend = " + dend);
}
return null;
}
};

InputFilter[] oldFilters = et.getFilters();
InputFilter[] newFilters = new InputFilter[oldFilters.length + 1];
System.arraycopy(oldFilters, 0, newFilters, 0, oldFilters.length);
newFilters[oldFilters.length] = filter;
et.setFilters(newFilters);
}


With this I can see that source will remain the same, if the maxLength is exceeded, but the Spanned dest changes the way it should, deleting the chars of text while pressing backspace.


Now what is going wrong here? Is this a bug? Because I don't think this behaviour is meant as default.


Edit:


The suggested way by Sandeep Kumar using pure Java to set the maxLength leads to the same result.



et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});


BTW, I'm using Android 4.4.2.


No comments:

Post a Comment