HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Remove useless whitespace from styled string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
whitespaceremoveuselessfromstyledstring

Problem

I have a big string resource (basically the "about" text of the application) which contains styles (such as `, etc.). The string resource is written on multiple lines, like this:

About\n
Lorem ipsum dolor sit amet and all that stuff...\n
\n
More stuff.


Now, just like in HTML, Android treats actual new lines (not the special
\n`) as spaces, so the text ends up looking something like this:

About
  Lorem ipsum dolor sit
amet and all that
stuff...

  More stuff.


Which looks pretty stupid. Now, I have two options:

  • Write the whole thing on one line. I did not go with this because:



  • It would be a pretty big line.



  • The text needs to be translated, and putting it all on one line would give the translators a great headache.



  • Remove the unneeded whitespace programatically.



I went with the second solution, but I'm not sure my implementation is optimal:

CharSequence aboutText = getText(R.string.about_text);

SpannableStringBuilder ssb = new SpannableStringBuilder(aboutText);
for (int i=0; i < ssb.length()-1; i++) {
    if (ssb.charAt(i) == '\n' && ssb.charAt(i+1) == ' ') {
        ssb.replace(i+1, i+2, "");
    }
}

this.aboutText = (TextView) findViewById(R.id.about_text);

this.aboutText.setText(ssb);


It seems very hackish, but I could not find a better way. Is there a better way?

Solution

The answer is to put the newlines at the start of each line, directly before the text.

About
    \nLorem ipsum dolor sit amet and all that stuff...
    \n\nMore stuff.


Therefore all the redundant whitespace appears at the end of each line (e.g. after "About") where it doesn't affect the appearance of your text.

Code Snippets

<string name="about_text"><big><b>About</b></big>
    \nLorem ipsum dolor sit amet and all that stuff...
    \n\nMore stuff.
</string>

Context

StackExchange Code Review Q#3099, answer score: 9

Revisions (0)

No revisions yet.