Skip to content

Instantly share code, notes, and snippets.

@VAdaihiep
Created July 2, 2016 04:01
Show Gist options
  • Save VAdaihiep/ff36a85a1b110275c389056e09e5ac93 to your computer and use it in GitHub Desktop.
Save VAdaihiep/ff36a85a1b110275c389056e09e5ac93 to your computer and use it in GitHub Desktop.
Format money. For an example: 10000 -> 10.000
public class MoneyFormatEditText extends EditText {
public MoneyFormatEditText(Context context) {
super(context);
setupTextWatcher();
}
public MoneyFormatEditText(Context context, AttributeSet attrs) {
super(context, attrs);
setupTextWatcher();
}
public MoneyFormatEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupTextWatcher();
}
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String money = CommonFunc.standardizedMoney(stringMoneyToInt(s.toString()));
removeTextChangedListener(textWatcher);
setText(money);
setSelection(money.length());
addTextChangedListener(textWatcher);
}
};
private int stringMoneyToInt(String money) {
money = money.replaceAll("\\.", "");
try {
return Integer.parseInt(money);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public int getMoney() {
Editable money = super.getText();
return stringMoneyToInt(money.toString());
}
private void setupTextWatcher() {
setInputType(InputType.TYPE_CLASS_NUMBER);
addTextChangedListener(textWatcher);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment