Issue
I am trying to create an IInputFilter for an EditText in my Xamarin Android app. I created the class below to do this. It works fine until I enter an invalid character. It filters the invalid character as expected, but after that the source includes all valid characters entered since the invalid one.
Key "a" - source = "a"
Key "b" - source = "b"
Key "," - source = "," (this is an invalid character so we return empty string)
Key "c" - source = "c"
Key "d" - source = "cd" (why not just "d"?)
Key "e" - source = "cde" (and so on)
public class AlphaFilter : Java.Lang.Object, IInputFilter
{
public Java.Lang.ICharSequence FilterFormatted(Java.Lang.ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
Java.Lang.String strResult;
bool blnValidated = source.ToString() == string.Empty || source.ToString().All(Char.IsLetterOrDigit);
if (blnValidated)
{
strResult = new Java.Lang.String(source.ToString());
}
else
{
strResult = new Java.Lang.String(string.Empty);
}
return strResult;
}
}
Solution
Found the problem. When the character is valid you just return null. Here is the working code:
public class AlphanumericFilter : Java.Lang.Object, IInputFilter
{
public Java.Lang.ICharSequence FilterFormatted(Java.Lang.ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
Java.Lang.String strResult;
bool blnValidated = source.ToString() == string.Empty || source.ToString().All(Char.IsLetterOrDigit);
if (blnValidated)
{
strResult = null;
}
else
{
strResult = new Java.Lang.String(string.Empty);
}
return strResult;
}
}
Answered By - P. Mancini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.