Change android text color from string

Hi, I am creating an android text that contains json. This is normal, but I want to change the color of part of the text view .. I don’t know how

here are 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); 

The above code is excellent ... which sets all the value in the text view, but I want to change the color of "Title", "Tender ID", "Quantity" , etc. from string s please help

+3
android
source share
5 answers

You can set the text as html:

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

Use covers

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); } 
+1
source share

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>"); } 

Output Example:

enter image description here

+1
source share

You can use Spanned for this.

  Spanned sText=Html.fromHtml("<font color="#C3003">Title:</font> " ); txt.setText(sText); 
0
source share
  Spannable WordtoSpan = new SpannableString(text); WordtoSpan.setSpan(new ForegroundColorSpan(Color.WHITE), text.length, (text + nextString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); myTextView.setText(WordtoSpan); 
0
source share

All Articles