Skip to content

Instantly share code, notes, and snippets.

@xuhaibahmad
Created September 18, 2017 12:08
Show Gist options
  • Save xuhaibahmad/2cfac981b50720c8a22af16ebf54bb58 to your computer and use it in GitHub Desktop.
Save xuhaibahmad/2cfac981b50720c8a22af16ebf54bb58 to your computer and use it in GitHub Desktop.
Text Input Filter to limit the number of decimal places
package com.mindscollide.baycho.utils;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.DigitsKeyListener;
/**
* Created by Zuhaib on 5/11/2017.
* <p>
* Text {@link android.text.InputFilter} to limit the number of decimal places
*/
public class DecimalPlacesFilter extends DigitsKeyListener {
private int mDigits = 2;
/**
* Returns new instance of {@link DecimalPlacesFilter}
*
* @param decimalPlaces The number of decimal places allowed
* @param isSigned The flag for value being signed
*/
public DecimalPlacesFilter(int decimalPlaces, boolean isSigned) {
super(isSigned, true);
mDigits = decimalPlaces;
}
/**
* Sets the decimal places limit
*
* @param decimalPlaces The number of decimal places allowed
*/
public void setDigits(int decimalPlaces) {
mDigits = decimalPlaces;
}
@Override
public CharSequence filter(CharSequence source, int sourceStart, int sourceEnd,
Spanned destination, int destStart, int destEnd) {
final CharSequence text = super.filter(source, sourceStart,
sourceEnd, destination, destStart, destEnd);
// if changed, replace the source
if (text != null) {
source = text;
sourceStart = 0;
sourceEnd = text.length();
}
int sourceLength = sourceEnd - sourceStart;
// return if text is empty
if (sourceLength == 0) {
return source;
}
int destLength = destination.length();
// Find the position of the decimal .
for (int currentLocation = 0; currentLocation < destStart; currentLocation++) {
if (destination.charAt(currentLocation) == '.') {
// Being here means, that a number has been inserted after the dot
// Check if the amount of digits is right
return (destLength - (currentLocation + 1) + sourceLength > mDigits)
? ""
: new SpannableStringBuilder(source, sourceStart, sourceEnd);
}
}
for (int i = sourceStart; i < sourceEnd; ++i) {
if (source.charAt(i) == '.') {
// Being here means, dot has been inserted
// Check if the amount of mDigits is right
if ((destLength - destEnd) + (sourceEnd - (i + 1)) > mDigits)
return "";
else
break;
}
}
// If the dot is after the inserted part, nothing can break
return new SpannableStringBuilder(source, sourceStart, sourceEnd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment