-1

Is it possible to set colours of strings used in a text view programmatically? I tried using this but it doesn't work.

TextView txt = (TextView)v.findViewById(R.id.textView1);
        txt.setText(Html.fromHtml("<font color='#0099CC'>@string/app_name</font>" +
                        "<font color='#995676'> @string/app_description</font>" +
                        "<font color='#55GGFES'> @string/app_version</font>"
        ));
wbk727
  • 8,017
  • 12
  • 61
  • 125
  • Nope, because I need to use multiple strings in 1 text view – wbk727 Jun 24 '15 at 21:10
  • we have another question http://stackoverflow.com/questions/10140893/android-multi-color-in-one-textview which is actually a duplicate of another :) sorry, didn't read totally carefully – bbill Jun 24 '15 at 21:11
  • If it is a duplicate, please remove it. – PJTraill Jun 24 '15 at 21:23

2 Answers2

3

You can, but not this easily. You can't just inject @string/ inside of a string in Java that way. What you can use is context.getResources().getString(R.id.app_name); to get the name. So like this:

    txt.setText(Html.fromHtml("<font color='#0099CC'>"+
         context.getResources().getString(R.id.app_name)+"</font>"+
         "<font color='#995676'>"+
         context.getResources().getString(R.id.app_description)+"</font>"));
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

You can also use a spannable.

String mString = context.getResources().getString(R.id.app_name);
Spannable coloredSpan = new SpannableString(mString);        
//Spannable.setSpan(Object what, int start, int end, int flags)

coloredSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 0, mString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

txt.setText(coloredSpan);
charliebeckwith
  • 1,449
  • 11
  • 29