1

I am trying to change the color of certain text in my TextView, and I am aware of using Spannable class from this Question.

My issue is that my text is added dynamically as a return value from an SQLite database query.

Can I still use Spannable, if so then how?

Code section where text set in TextView:

case R.id.btnAvgAttSearch:

            final String entry = avgEntered.getText().toString();
            // convert from string value to int
            int avgValToSearch = Integer.parseInt(entry); //

            // /setting results equal to return val of search
            results = db.getSpecificAverageAtt(avgValToSearch);


            tvResults.setText(listToString(results));

             }

            break;

Example output in TextView, note that circled areas are the lines I wish to be in red:

enter image description here

EDIT:

ListToString Method:

public static String listToString(List<?> list) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            result += "" + list.get(i) + "\n\n";
        }
        return result;
    }
Community
  • 1
  • 1
codeme2020
  • 853
  • 2
  • 13
  • 20

1 Answers1

0

Just change ListToSTring to return a Spannable, for instance:

public static Spannable listToString(List<?> list) {
    SpannableStringBuilder result = new SpannableStringBuilder();
    for (int i = 0; i < list.size(); i++) {
        result.append(list.get(i)).append("\n\n");
    }
    return result;
}

Then you can programmatically add spans to the result.

Spannable text = listToString(results);
text.setSpan( /*.. span goes here */ );
tvResults.setText(text);
Barend
  • 17,296
  • 2
  • 61
  • 80