Sunday, November 9, 2008

EditText with limited number of characters

I just fough with the SDK for quite some time to find this one.

As a average modern programer, I started by looking on the internet, but didn't find anything. I imagine I didn't search the right sites ( no comments on this please ! )

So this is what I came up with :


editEntryView.setOnKeyListener
(
new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
EditText NameView = (EditText ) editEntryView.findViewById( R.id.PlayerName );
String Name = NameView.getText().toString();
if ( Name.length() >= 8 )
{
if ( keyCode != KeyEvent.KEYCODE_DEL )
return true;
}
return false;
}
}
);

I imagine that there are many things that should be cleaner here, but, hey !, it works, and that so good for me !

I fought for some time, because I was looking for a way to call a parent method when I didn't treat the case and decided to pass for this letter.
Actually, the behaviour is just the opposite :
if you return true, it means you dealed with the entry, so the treatment will stop here.
if you return false, it means you didn't deal with the entry, so it will be passed to the next listener.

Actually, a classic listener pattern !



Next thing : enter as a ok-click entry !

4 comments:

Unknown said...

An easier way would be to do this:
editText.setFilters(new InputFilter[]
{
new InputFilter.LengthFilter(maxLength) });

AndroidBlogger said...

Yes, you're completely right.
I missed the easy versions for some time (the doc is quite obscur at some time ).
But I finally found it and post about it here :
numeric editText and EditText with max number of characters... yes, again !And the Xml version is even simpler :)

Thanks for your input !

Indiana said...

Hi AndroidBlogger,
I would like to build an EditText control with dynamically symbol (non-character) filtering. Do you have any idea of this simple funciton, or could you please give me some hints or examples? Thank you!

AndroidBlogger said...

Hi Indiana,

If you want a post treatment to validate each keys entered on this edit text, I had a solution here :

http://androidblogger.blogspot.com/2008/12/edittext-numeric-only.html


Hope it helps...