Created
May 23, 2024 16:17
-
-
Save sajjadyousefnia/1be380ac2e3636f5fc453d0304fa5ae8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.widget.EditText | |
import java.text.DecimalFormatSymbols | |
fun EditText.addThousandSeparator() { | |
this.addTextChangedListener(object : TextWatcher { | |
private var current = "" | |
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(s: Editable?) { | |
if (s.toString() != current) { | |
val userInput = s.toString().replace("[^\\d]".toRegex(), "") | |
if (userInput.isNotEmpty()) { | |
val formatted = StringBuilder() | |
val symbols = DecimalFormatSymbols.getInstance() | |
val separator = symbols.groupingSeparator | |
var counter = 0 | |
for (i in userInput.length - 1 downTo 0) { | |
formatted.append(userInput[i]) | |
counter++ | |
if (counter % 3 == 0 && i != 0) { | |
formatted.append(separator) | |
} | |
} | |
current = formatted.reverse().toString() | |
val selectionStart = [email protected] | |
val newSelectionStart = calculateCursorPosition(selectionStart, userInput, current) | |
[email protected](this) | |
[email protected](current) | |
[email protected](newSelectionStart) | |
[email protected](this) | |
} | |
} | |
} | |
}) | |
} | |
private fun calculateCursorPosition(start: Int, originalText: String, formattedText: String): Int { | |
val symbols = DecimalFormatSymbols.getInstance() | |
val separator = symbols.groupingSeparator | |
var newPosition = start | |
for (i in 0 until start) { | |
if (i < formattedText.length && formattedText[i] == separator) { | |
newPosition++ | |
} | |
} | |
return newPosition.coerceAtMost(formattedText.length) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment