Sunday, December 28, 2008

Numeric only editText

Based on what we have done yesterday (here ), it's very easy to limit our EditText to whatever we want !

And a common application would be to implement a numeric only editText :

Here's a first int version :

editEntryView.addTextChangedListener
(
new TextWatcher()
{
String CurrentWord;
private boolean IsValid( CharSequence s )
{
for ( int i = 0; i < s.length(); i ++ )
{
if ( !Character.isDigit( s.charAt(i)))
return false;
}
return true;
}
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
CurrentWord = s.toString();
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if( !IsValid(s) )
{
editEntryView.setText(CurrentWord);
editEntryView.setSelection( start );
}
}
}
);


That simple !

And if you want any decimal numeric, just write another IsValid method :

private boolean IsValid( CharSequence s )
{
// special autorization for empty field
if (s.length() == 0)
return true;
// special autorization for '.', in order to enter .5
if (s.length() == 1 && s.charAt(0) == '.')
return true;
try
{
Double.parseDouble( s.toString() );
return true;
}
catch( Exception e)
{
return false;
}
}

We just have to be careful for special cases like the empty field, or just a dot ( this is the needed transition to enter something like .5 ).

And we must take into account those special cases when we will validate the entry.

1 comment:

fortywinks32 said...



When you blog about something that you are passionate of, the rest will just follow. You spend time on it because you love doing it, your contents are great because it is of interest to you, etc. The point is you blog for your own personal gratification.

beds
bed
mattress
mattresses