代码之家  ›  专栏  ›  技术社区  ›  Ayhem

更改部分EditText文本颜色[关闭]

  •  -3
  • Ayhem  · 技术社区  · 8 年前

    是否有方法更改EditText文本部分的颜色?
    在我的应用程序中,用户可以使用他们的用户名在帖子中标记他的朋友,现在我想在用户仍在键入时将用户名颜色更改为蓝色,这样他就知道他成功地标记了他的朋友(就像在Facebook中标记朋友一样)
    我仍然没有任何代码,因为我不知道如何开始!有什么帮助吗?

    2 回复  |  直到 8 年前
        1
  •  0
  •   Bundeeteddee    8 年前

    如果您只需要对 EditText ,您可以使用 Spannable 在这种情况下 ForegroundColorSpan 会是个好的开始。

    简化的解决方案类似于:

    String usernameToLookFor = "michael";
    String myString = "Welcome world to michael !!";
    
    //Create spannable string
    SpannableString spannableString = new SpannableString(myString);
    
    //Determine the start and end of the span i.e. which section you want colored
    //Note: loop it if username appears multiple times in main string
    int usernameStart = myString.indexOf(usernameToLookFor);
    int usernameEnd = usernameStart + usernameToLookFor.length;
    
    //Apply color spannable to SpannableString
    spannableString.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.highlighted_color)),usernameStart, usernameEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    
    //Set spannable to edit text
    myEditText.setText(spannableString);
    

    很粗糙的回答。希望能有所帮助。

        2
  •  0
  •   Felipe R. Saruhashi    8 年前

    可以将代码中的HTML插入到文本视图中,然后可以在文本的特定部分定义颜色:

    myTextView
    .setText(
      Html.fromHtml(
       "Your text<span color='<your color>'>colored part</span> rest of your text"
    ));
    
    推荐文章