Remove characters from a paired CharSequence

I have the following input in a String: "Hello # this # is # sample # text."

It sets the background color for all elements between # characters. Here is what I got so far:

public static CharSequence colorBackground(CharSequence text) { Pattern pattern = Pattern.compile("#(.*?)#"); Spannable spannable = new SpannableString( text ); if( pattern != null ) { Matcher matcher = pattern.matcher( text ); while( matcher.find() ) { int start = matcher.start(); int end = matcher.end(); CharacterStyle span = new BackgroundColorSpan(0xFF404040); spannable.setSpan( span, start, end, 0 ); } } return spannable; } 

Setting the background color works, but the placeholders # are also stylized. How to delete them before returning the result, because the ReplaceAll method does not exist for CharSequence?

I use this function for TextView line styles in ListView. After adding this style function, it is a little slower in the emulator. Maybe I should approach him in some other way, for example. use custom textview with custom drawing function?

+7
source share
2 answers

It sounded like a fun thing to try to understand.

The key was SpannableStringBuilder . With SpannableString, the text itself is unchanged, but with SpannableStringBuilder, the text and layout can be changed. With that in mind, I slightly modified your snippet to do what you want:

 public static CharSequence colorBackground(CharSequence text) { Pattern pattern = Pattern.compile("#(.*?)#"); SpannableStringBuilder ssb = new SpannableStringBuilder( text ); if( pattern != null ) { Matcher matcher = pattern.matcher( text ); int matchesSoFar = 0; while( matcher.find() ) { int start = matcher.start() - (matchesSoFar * 2); int end = matcher.end() - (matchesSoFar * 2); CharacterStyle span = new BackgroundColorSpan(0xFF404040); ssb.setSpan( span, start + 1, end - 1, 0 ); ssb.delete(start, start + 1); ssb.delete(end - 2, end -1); matchesSoFar++; } } return ssb; } 

I don’t have much experience with Spannables in general, and I don’t know if the way I deleted "#" is the best method, but it works.

+12
source

How to delete them before returning the result, because the ReplaceAll method does not exist for CharSequence?

You can take the Html.fromHtml() approach - create a SpannedString , don't try to modify it in place.

0
source

All Articles