Created
November 15, 2016 21:28
-
-
Save fpadoan/fb2a1577d78997e30b27d1a6519fcca9 to your computer and use it in GitHub Desktop.
Simple currency TextWatcher, providing a quick and dirty way to generate formatted price strings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LocalCurrencyTextWatcher implements TextWatcher { | |
private String separator | |
String beforeText = ""; | |
String finalText = ""; | |
boolean changing = false; | |
public LocalCurrencyTextWatcher(String separator) { | |
this.separator = separator; | |
} | |
@Override | |
public void beforeTextChanged(CharSequence s, int start, int count, int after) { | |
if (s.toString().length() > 0) { | |
beforeText = s.toString(); | |
} | |
} | |
@Override | |
public void onTextChanged(CharSequence s, int start, int before, int count) { | |
if (changing) return; | |
String sequence = s.toString(); | |
if (sequence.length() > 0 && count > 0) { | |
if (beforeText.contains(separator)) { | |
String newPart = s.subSequence(start, start + count).toString(); | |
char sepChar = separator.charAt(0); | |
if (newPart.contains(separator)) { | |
// prevent second decimal separator | |
StringBuffer buffer = new StringBuffer(sequence); | |
int removeIndex = sequence.lastIndexOf(sepChar); | |
finalText = buffer.replace(removeIndex, removeIndex + 1, "").toString(); | |
} else if (sequence.substring(sequence.indexOf(sepChar) + 1).length() > 2) { | |
// limit cents part | |
int toRemove = 1; | |
finalText = sequence.substring(0, sequence.length() - toRemove); | |
} | |
else { | |
finalText = sequence; | |
} | |
} else { | |
finalText = sequence; | |
} | |
} else { | |
finalText = sequence; | |
} | |
} | |
@Override | |
public void afterTextChanged(Editable s) { | |
if (changing) { | |
// prevent infinite loop | |
changing = false; | |
beforeText = ""; | |
finalText = ""; | |
} else if (beforeText.length() > 0 && | |
!finalText.equals(s.toString())) { | |
changing = true; | |
s.replace(0, s.length(), finalText); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment