i have 1 edittext maxLength = 30, but i can only type 6 character emoji dog => 1 emoji dog = 6 regular character. So please help me type 30 emoji dog. Thanks everyone.
[enter image description here][1]
CodePudding user response:
When someone types an emoji, you can call .length
on that emoji, then increase your max character count by that amount. (You would have to remember your original character count and use that on your UI if you wanted to hide the magic).
i.e. when someone types a "dog" then you increase your max count from 30 to 35. (1 has been used and a dog usually counts for 6)
Ref:
- https://twitter.com/riggaroo/status/1148278279713017858
- https://developer.android.com/reference/java/text/BreakIterator
- https://lemire.me/blog/2018/06/15/emojis-java-and-strings/
- https://developer.android.com/reference/kotlin/androidx/emoji/text/EmojiCompat
CodePudding user response:
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
oldTextString = charSequence.toString()
}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
var newTextString = editable.toString()
if (!oldTextString.equals(newTextString)) {
if (Character.codePointCount(
newTextString,
0,
newTextString.length
) > maxCharactersAllowed
) {
newTextString = oldTextString
}
editText.setText(newTextString)
editText.setSelection(newTextString.length)
}
}
})