Created
May 23, 2024 16:08
-
-
Save sajjadyousefnia/33e183b1fb6282935a31fc20872b4903 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 selectionEnd = [email protected] | |
[email protected](this) | |
[email protected](current) | |
[email protected](calculateCursorPosition(selectionStart, selectionEnd, current)) | |
[email protected](this) | |
} | |
} | |
} | |
}) | |
} | |
private fun calculateCursorPosition(start: Int, end: Int, text: String): Int { | |
val symbols = DecimalFormatSymbols.getInstance() | |
val separator = symbols.groupingSeparator | |
var newPosition = start | |
for (i in 0 until start) { | |
if (text[i] == separator) { | |
newPosition++ | |
} | |
} | |
return newPosition.coerceAtMost(text.length) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment