更改文本视图的一些字符串的颜色

change color some string of textview

如何改变文本视图中字符串的某些部分的颜色,值来自json。我同时使用 Spannable class 和 through html,但不会更改。

  if(jobject.has("posts")){

               JSONArray ar= jobject.getJSONArray("posts");
               String value=""+ar.length();
               Profile.this.post.setText(value);
               for(int i=0;i<ar.length();i++){
                   JSONObject a= ar.getJSONObject(i);
                   Pojo_profile po= new Pojo_profile();
                  // po.setUsername();
                   String blue = object.getString("user_login");

                   po.setData(Html.fromHtml("<font color='#FF0000'>"+blue+"</font>")+" "+a.getString("text_post"));


                   profile.add(po);
               }
textView.setText(Html.fromHtml("*your html text*"));

仅在设置文本时调用 Html.fromHtml

使用跨度。

示例:

final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");

// Span to set text color to some RGB value
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

// Span to make text bold
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

// Set the text color for first 4 characters
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

// make them also bold
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

yourTextView.setText(sb);

根据您的问题表明您需要在单个 textView 上设置两种或多种文本颜色,然后下一行应该可以工作

      textView.setText(Html.fromHtml("blue" +"<font color=\"#000099\">"  + a.getString("text_post") + "</font>"));

SDK>=14

中使用 setAllCapsfalse
 if (Build.VERSION.SDK_INT >= 14) {
        textView.setAllCaps(false);

    }

然后使用

textView.setText(Html.fromHtml("*your html text*"));