Created
June 5, 2022 17:26
-
-
Save felipedavi/f2a8a56c80a8d7b99dd361950e614cc5 to your computer and use it in GitHub Desktop.
Currency Mask - Real BRL
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
import android.text.Editable | |
import android.text.TextWatcher | |
import android.util.Log | |
import android.widget.EditText | |
import java.math.BigDecimal | |
import java.text.DecimalFormat | |
import java.text.NumberFormat | |
import java.util.* | |
class CurrencyMask(private val editText: EditText) : TextWatcher { | |
companion object { | |
private const val replaceRegex: String = "[R$,.\u00A0]" | |
private const val replaceFinal: String = "R$,.\u00A0" | |
} | |
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { | |
} | |
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { | |
} | |
override fun afterTextChanged(editable: Editable?) { | |
try { | |
val stringEditable = editable.toString() | |
if (stringEditable.isEmpty()) return | |
editText.removeTextChangedListener(this) | |
val cleanString = stringEditable.replace(replaceRegex.toRegex(),"") | |
val parsed = BigDecimal(cleanString) | |
.setScale(2, BigDecimal.ROUND_FLOOR) | |
.divide(BigDecimal(100), BigDecimal.ROUND_FLOOR) | |
val decimalFormat = NumberFormat.getCurrencyInstance(Locale("pt", "BR")) as DecimalFormat | |
val formatted = decimalFormat.format(parsed) | |
val stringFinal = formatted.replace(replaceFinal, "") | |
editText.setText(stringFinal) | |
editText.setSelection(stringFinal.length) | |
editText.addTextChangedListener(this) | |
} catch (e: Exception) { | |
Log.e("ERROR", e.toString()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment