简体   繁体   中英

How to color some part of string in android?

I have implemented a search list It outputs the matched strings from pattern in a given list view. Now I want to color only that part of my string which matches the pattern. Please help me. Thanks in advance.

You're looking for spannable: http://developer.android.com/reference/android/text/Spannable.html

Example:

SpannableString demotext = new SpannableString("All your base are belong to me");
// Make 'All' (chars 0 to 3) red
demotext.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, 0);
((TextView) getView().findViewById(R.id.fragment_disclaimer_title)).setText(demotext);

http://www.chrisumbel.com/article/android_textview_rich_text_spannablestring http://eazyprogramming.blogspot.co.uk/2013/06/spannable-string-in-android-url-span.html

for color a part of your string you can do like this :

String styledText = "This is <font color='red'>simple</font>.";
textView.setText(Html.fromHtml(styledText), TextView.BufferType.SPANNABLE);

just after modify this.

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