【发布时间】:2018-05-12 18:57:15
【问题描述】:
我有一个edittext,当用户输入它时,@mentions 和 #hashtags 的颜色应该会改变。我用过textwatcher,但它很慢,打字时会漏掉一些字符。我很想听听替代方案。
这是我的代码:
var previousString = ""
override fun initTextAreaView() {
if(twitterAvailable && twitterIsEnabled) CHARLIMIT = 280
if(!twitterIsEnabled && linkedInAvailable && linkedInIsEnabled) CHARLIMIT = 700
charcount.text = CHARLIMIT.toString()
content.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(s.toString()!=previousString)checkMentionsAndHashtags(s.toString())
}
})
}
var textSpanList: ArrayList<TextSpan> = ArrayList()
private fun checkMentionsAndHashtags(s: String) {
previousString = s
textSpanList = ArrayList()
val words = s.split(" ")
for(word in words){
if(word.length>0) {
if (word[0] == '@' || word[0] == '#') {
val n = s.lastIndexOf(word)
textSpanList.add(TextSpan(n, (n+word.length)))
}
}
}
changeTextColor(s, SpannableStringBuilder(s))
}
private fun changeTextColor(s: String = "", str: SpannableStringBuilder = SpannableStringBuilder("")) {
Log.d("TEXTSPANS", textSpanList.toString())
if(textSpanList.size>0){
for(span in textSpanList) {
str.setSpan(ForegroundColorSpan(resources.getColor(R.color.colorPrimary)), span.startPos, span.endPos, 0)
}
}
val cursorPos = content.selectionEnd
content.text = str
content.setSelection(cursorPos)
}
【问题讨论】:
-
我找到了一个library。这可能对你有帮助
-
@HarshadPrajapati 它不适用于edittext。我也在处理光标位置,所以我需要一些东西来处理edittext。谢谢你的建议:)
-
查看我更新的帖子,它会对您有所帮助.. 它对我来说很好..
-
在 kotlin 中查看我的解决方案以获取标签,类似地您可以提及; stackoverflow.com/a/57481803/2522797