Skip to content

Instantly share code, notes, and snippets.

@chalisegrogan
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save chalisegrogan/a08ae910e4f1b2a97b78 to your computer and use it in GitHub Desktop.

Select an option

Save chalisegrogan/a08ae910e4f1b2a97b78 to your computer and use it in GitHub Desktop.
Limit Decimal Places in Android EditText: Xamarin implementation of IInputFilter
/// <summary>
/// Reference: Xamarinifies http://stackoverflow.com/a/6264829/651952
/// </summary>
public class DecimalDigitsInputFilter : Java.Lang.Object, IInputFilter
{
public ICharSequence FilterFormatted(ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
int dotPos = -1;
int len = dest.Length();
for (int i = 0; i < len; i++)
{
char c = dest.CharAt(i);
if (c == '.' || c == ',')
{
dotPos = i;
break;
}
}
if (dotPos >= 0)
{
// protects against many dots
if (source.Equals(new Java.Lang.String(".")) || source.Equals(new Java.Lang.String(",")))
{
return new Java.Lang.String("");
}
// if the text is entered before the dot
if (dend <= dotPos)
{
return null;
}
if (len - dotPos > DecimalDigits)
{
return new Java.Lang.String("");
}
}
return null;
}
private readonly int DecimalDigits;
public DecimalDigitsInputFilter(int decimalDigits)
{
this.DecimalDigits = decimalDigits;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment