简体   繁体   中英

How to give color to string in the java code of android?

How to give color to string: Example:

String str="Hello Android";

How to give color to the above string?

Also how to give red color to string "cancel" the following :

final String[] items = { "Switch Off", "Timer Settings","Cancel"};

Use spannable class to do this:

 Spannable WordtoSpan = new SpannableString(myString);        
            WordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
final CharSequence[] items = {
    "Switch Off",
    "Timer Settings",
    Html.fromHtml("<font color=\"red\">Cancel</font>"),
};

Instead of string use TextView and change the background of it eg

  TextView tv;
  tv.setText("yourText");
  tv.setTextColor(Color.CYAN);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM