title: Android edittext color change for @mentions and #hashtags while typing
body: <p>I have a <code>edittext</code> and when the user types in it the color of <strong>@mentions</strong> and <strong>#hashtags</strong> should change. I have used <code>textwatcher</code> but it is laggy and it misses out some characters while typing. I would love to hear about alternatives.</p>
  
  <p>This is my code:    </p>
  
  <pre><code>var previousString = ""
          override fun initTextAreaView() {
              if(twitterAvailable &amp;&amp; twitterIsEnabled) CHARLIMIT = 280
              if(!twitterIsEnabled &amp;&amp; linkedInAvailable &amp;&amp; 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&lt;TextSpan&gt; = ArrayList()
          private fun checkMentionsAndHashtags(s: String) {
              previousString = s
              textSpanList = ArrayList()
              val words = s.split(" ")
              for(word in words){
                  if(word.length&gt;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&gt;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)
          }
  </code></pre>