Hey i am creating a android textview which contains come from json.. It is fine but i want to change color of the part of the text view.. dont know how
here is my details-
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);
On the above code is fine..that sets all the value in the text view but i want to change the color of "Title" ,"Tender id", "Quantity" etc.. from above string s please help
您可以将文本设置为html:
txt.setText(Html.fromHtml("your <font color='#FF0000'>content</font>");
Use spans
Example:
{
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);
}
Here is a solution specific to your case:
Update your code as follows:
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);
Define a helper method in the same class and use it:
private Spanned getColorString(String str) {
return Html.fromHtml("<font color='#FFFF00'>" + str + "</font>");
}
Sample output:
you can use Spanned also for that.
Spanned sText=Html.fromHtml("<font color="#C3003">Title:</font> " );
txt.setText(sText);
Spannable WordtoSpan = new SpannableString(text);
WordtoSpan.setSpan(new ForegroundColorSpan(Color.WHITE), text.length, (text +
nextString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(WordtoSpan);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.