Android "Simple Method for formatting textview

Source: Internet
Author: User
Wednesday, August 4, 2010

Easy Method for formatting Android textviews

Android textviews don't have an easy method for changing the style of a substring of its text. You may have wanted to do something liketextView.setTextColor(Color.RED, 10, 20);In order to set the 10th to the 20th characters red. I'll show you
A method of making this easy to do; not just with colors, but with all sorts of styles.

Using regular HTML tags in strings

You do have a limited option to format your strings without any programmatic methods. In strings. XML, where you define your strings, you can use the simple HTML format tags<b>,<i>, And<u>For bold, italics, and underlining,
Respectively. for example, <string name = "text1"> This text uses <B> bold </B> and <I> italics </I> by using inline tags such as <B> within the string file. </string>

A textview with this string will appear as: This text usesBoldAndItalicsBy using inline tags such as <B> within the string file.
Unfortunately, you cannot use any more HTML tags than that. In order to have some nice inline styles, we'll need to use characterstyles.
This class has implements sub-classes, and allows you to do everything from changing the text appearance (like foregroundcolorspan,
To more complicated things like making clickable links (clickablespan)
And images (imagespan ).
Charsequences

A quick note about how this works. Skip to the next section if you don't care.TextView, Along with your other android classes which use formatted text, don't just use simpleStrings. They useCharSequences.
Get this:CharSequenceIsMore abstractThanString;StringIs a sub-classCharSequence.CharSequenceDefines a series of characters, such as a regular string, but it cocould
Also define a series of characters with formatting, such asSpannableString. Internally, what we will do to change the middle ofTextView'S text is to add spans to its text. More precisely, we will addCharacterStylesTo
The textview'sCharSequence(Text), which isSpannableString.
Format Text dynamically

Here's a handy utility method which will take in some text, and return the Text formatted. The key is to surround the text you want with tokens such"##". The tokens will be removed in the returned result.
For example, ifTextViewHas its text set"Hello, ##world##!"And you wantworldTo be in red, callsetSpanBetweenTokens("Hello ##world##!", "##", new ForegroundColorSpan(0xFFFF0000));Will return
TextHello, world!WithworldIn red. Note that you can send multiple spans as parameters to this method.

/**
* Given either a spannable string or a regular string and a token, apply
* The given characterstyle to the span between the tokens, and also
* Remove tokens.
* <P>
* For example, {@ code setspanbetweentokens ("Hello ## world ##! ","##",
* New foregroundcolorspan (0xffff0000);} will return a charsequence
* {@ Code "Hello world! "} With {@ code world} in red.
*
* @ ParamText the text, with the tokens, to adjust.
* @ ParamToken the token string; there shocould be at least two instances
* Of token in text.
* @ ParamCS the style to apply to the charsequence. Warning: you cannot
* Send the same two instances of this parameter, otherwise
* The second call will remove the original span.
* @ ReturnA spannable charsequence with the new style applied.
*
* @ SeeHttp://developer.android.com/reference/android/text/style/CharacterStyle.html
*/
Public  StaticCharsequence setspanbetweentokens (charsequence Text,
String Token, Characterstyle... CS)
{
// Start and end refer to the points where the span will apply
Int  Tokenlen= Token. Length ();
Int  Start= Text. Tostring (). indexof ( Token) + Tokenlen;
Int  End= Text. Tostring (). indexof ( Token, Start);

If(Start>-1 &&End>-1)
{
// Copy the spannable string to a mutable spannable string
SpannablestringbuilderSSB=NewSpannablestringbuilder (Text);
For(CharacterstyleC:CS)
SSB. Setspan (C,Start,End, 0 );

// Delete the tokens before and after the span
SSB. Delete (End,End+Tokenlen);
SSB. Delete (Start-Tokenlen,Start);

Text=SSB;
}

Return Text;
}

Clickable Spans

One of the spans you can set your text to is a clickablespan.
You may have added this and wondered why anything didn't happen when you clicked on the link. well, you need to have one extra step to let Android know that there is a clickable link and it needs to be navigated. you need to setMovementMethodTo
TheTextView. You can investigate this further if you wish, or you can just see the sample code to make it work below (and it is also in the sample ):


// Adapted from linkify. addlinkmovementmethod (), to make links clickable.
//
Movementmethod M= Textview. Getmovementmethod ();
If(( M= Null) |! ( M  InstanceofLinkmovementmethod ))
{
Textview. Setmovementmethod (linkmovementmethod. getinstance ());
}

Sample Application

The sample application is a simple application with a fewTextViewsAndButton. The firstTextViewShows how you can setTextView'S text just by using HTML tags instrings.xml. The secondTextViewDemonstrates
How to change text dynamically, using the above utility method. When the button is clicked, it will first set some text red usingForegroundColorSpan. Second, it will set some text bold and italics usingStyleSpan. Third, it will
Make a generic link by setting some text to blue, underlining it (UnderlineSpan), And then creatingonClickMethod which executes some custom code usingClickableSpan. The final click demonstrates bothForegroundColorSpanAnd
ARelativeSizeSpan.

Project source code-Formattedtext.zip (7.22
KB)

Posted by Matt Quigley at 11: 13
PM 

Email
Thisblogthis! Share
To twittershare
To Facebook

Labels: Ui
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.