从字符串中更改android textview颜色

时间:2013-12-16 06:40:59

标签: android

嘿,我正在创建一个包含来自json的android textview .. 它很好,但我想改变文本视图部分的颜色..不知道如何

这是我的详细信息 -

JSONArray jArray= new JSONArray(result);

for(int i=0; i<jArray.length();i++)
{
JSONObject getjson=jArray.getJSONObject(i);

s= "Title: "            +getjson.getString("tender_title")+
   "\n\nTender id: "    +getjson.getString("tender_id")+
   "\n\nReference no:\n"+getjson.getString("tender_reference_no")+
   "\n\nQuantity: "     +getjson.getString("tender_item_details_quantity");

}

TextView txt=(TextView) findViewById(R.id.textView1);
txt.setText(s); 

在上面的代码很好..设置文本视图中的所有值,但我想更改“标题”,“投标ID”,“数量”等的颜色。从上面的字符串 s 请帮助

5 个答案:

答案 0 :(得分:2)

您可以将文本设置为html:

txt.setText(Html.fromHtml("your <font color='#FF0000'>content</font>");

答案 1 :(得分:1)

使用spans

示例:

{
   final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");
   final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); 

   // Span to set text color to some RGB value
   final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); 

   // Span to make text bold
   sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 

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

   // make them also bold
   yourTextView.setText(sb);
}

答案 2 :(得分:1)

以下是针对您的案例的解决方案:

按如下方式更新您的代码:

JSONArray jArray= new JSONArray(result);
Spanned spannedStr = null;
for(int i=0; i<jArray.length();i++)
{
    JSONObject getjson = jArray.getJSONObject(i);

    spannedStr = (Spanned) TextUtils.concat(getColorString("Title:"), getjson.getString("tender_title"), "\n\n",
            getColorString("Tender id:"), getjson.getString("tender_title"), "\n\n",
            getColorString("Reference no:"), getjson.getString("tender_title"), "\n\n",
            getColorString("Quantity:"), getjson.getString("tender_title"));

}
TextView txt=(TextView) findViewById(R.id.textView1);
txt.setText(spannedStr);

在同一个类中定义一个帮助器方法并使用它:

private Spanned getColorString(String str) {
    return Html.fromHtml("<font color='#FFFF00'>" + str + "</font>");
}

示例输出:

enter image description here

答案 3 :(得分:0)

你也可以使用Spanned。

 Spanned sText=Html.fromHtml("<font color="#C3003">Title:</font> "  );

txt.setText(sText);

答案 4 :(得分:0)

 Spannable WordtoSpan = new SpannableString(text);

 WordtoSpan.setSpan(new ForegroundColorSpan(Color.WHITE), text.length, (text +      
 nextString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

 myTextView.setText(WordtoSpan);
相关问题