[Android] is a gadget for textview with two-color text configuration Colorphrase

Source: Internet
Author: User
Tags getcolor

This article links http://blog.csdn.net/jan_s/article/details/51338944 , reprint please leave a message.


In the Android development process, often see the text in the focus of the field is required to change color, in order to show its particularity. This time most people will use the simpler way is to come out again new TextView, obviously very fast, but this is undoubtedly to add trouble to the layout, here is a simple tool to provide a colorphrase class, to help you solve this problem.


Watch the demo first


How to use:

1.mainactivity.java

public class Mainactivity extends Activity {private EditText edittext;private TextView textview;private button button; @Ov errideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); editText = (EditText) Findviewbyid (R.ID.EDITTEXT1); TextView = (TextView) Findviewbyid ( R.ID.TEXTVIEW1); button = (button) Findviewbyid (R.id.button1); Button.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {//Here is how to use: the main color of the text with "{}" to distinguish, and then the text style color processing, this is the work of colorphrase. String pattern = Edittext.gettext (). toString (); Charsequence chars = Colorphrase.from (pattern). Withseparator ("{}"). Innercolor (Getresources (). GetColor (R.color.in_ color). Outercolor (Getresources (). GetColor (R.color.out_color)). Format (); Textview.settext (chars);}});}

2.colorphrase.java-This is the main feature implementation class, which can be copied to the project.

public class Colorphrase {/** the unmodified original pattern. */private Final charsequence pattern;/** Cached result afte R replacing all keys with corresponding values. */private Charsequence formatted;/** * The constructor parses the original pattern into this doubly-linked list * of tokens S. */private Token head;/** When parsing, the current character. */private char curchar;private String separator;//default "{}" private int curcharindex;private int outercolor;//color th At outside the Separators,default 0xff666666private int. innercolor;//color that between the Separators,default 0xffa6454a /** indicates parsing is complete. */private static final int EOF = 0;/** * Entry point to this API. * * @throws IllegalArgumentException * If pattern contains any syntax errors. */@TargetApi (build.version_codes. Honeycomb) public static colorphrase from (Fragment F, int. Patternresourceid) {return from (F.getresources (), Patternresourceid);} /** * Entry point to this API. *  * @throws IllegalArgumentException * If pattern contains any syntax errors. */public static colorphrase from (View V, int. Patternresourceid) {return from (V.getresources (), Patternresourceid);} /** * Entry point to this API. * * @throws IllegalArgumentException * If pattern contains any syntax errors. */public static colorphrase from (Context C, int. Patternresourceid) {return from (C.getresources (), Patternresourceid);} /** * Entry point to this API. * * @throws IllegalArgumentException * If pattern contains any syntax errors. */public static colorphrase from (Resources R, Int. Patternresourceid) {return from (R.gettext (Patternresourceid));} /** * Entry point to this API; Pattern must be non-null. * * @throws IllegalArgumentException * If pattern contains any syntax errors. */public static colorphrase from (Charsequence pattern) {return new colorphrase (pattern);} Private Colorphrase (charsequence pattern) {Curchar = (pattern.length () > 0)? Pattern.charat (0): Eof;this.pattern = pattern;//Invalidate the cached formatted text.formatted = Null;separator = "{}"; Initialize the default Separatoroutercolor = 0xff666666;//initialize the default Valueinnercolor =0xffe6454a;// Initialize the default value}/** * Set the separator of the target,called after from () method.  * * @param _separator * @return */public colorphrase withseparator (String _separator) {if (Textutils.isempty (_separator)) {throw new IllegalArgumentException ("Separator must not be empty!");} if (_separator.length () > 2) {throw new IllegalArgumentException ("separator ' s length must not being more than 3 charactors !");} This.separator = _separator;return This;} /** * Init the outercolor * * @param _outercolor * @return */public colorphrase outercolor (int _outercolor) {This.outerco Lor = _outercolor;return This;} /** * Init the innercolor * * @param _innercolor * @return */public colorphrase innercolor (int _innercolor) {This.innerco Lor = _innercolor;return This;} /** * Cut the pattern with the separators and linked them with double link * structure; */private void Createdoublelinkwithtoken () {//A hand-coded lexer based on the idioms in//' Building recognizers by hand '. Http://www.antlr2.org/book/byhand.pdf.Token prev = null; Token next;while (next = token (prev)) = null) {//Creates a doubly-linked list of tokens starting with head.if (head = = NULL) head = Next;prev = Next;}} /** * Returns The next token from the input pattern, or NULL when finished * parsing. */private Token token (token prev) {if (Curchar = = EOF) {return null;} if (Curchar = = Getleftseparator ()) {char Nextchar = lookahead (); if (Nextchar = = Getleftseparator ()) {return Leftseparator ( prev);} else {return inner (prev);}} return outer (prev);} Private char Getleftseparator () {return Separator.charat (0);} Private char Getrightseparator () {if (separator.length () = = 2) {return Separator.charat (1);} Return Separator.charat (0);} /** * Returns the text after replacing all keys with values. * * @tHrows IllegalArgumentException * If any keys is not replaced. */public charsequence Format () {if (formatted = = NULL) {if (!checkpattern ()) {throw new IllegalStateException ("The Separat ORS don ' t match in the pattern! ");} Createdoublelinkwithtoken ();//Copy The original pattern to preserve all spans, such as bold,//italic, etc. Spannablestringbuilder sb = new Spannablestringbuilder (pattern); for (Token t = head; T! = null; t = t.next) {t.expand (SB); }formatted = SB;} return formatted;} /** * Check if the pattern has legal separators * * @return */private boolean checkpattern () {if (pattern = = null) {retur n false;} Char leftseparator = Getleftseparator (); char rightseparator = Getrightseparator (); stack<character> separatorstack = new stack<character> (); for (int i = 0; i < pattern.length (); i++) {char c ur = Pattern.charat (i), if (cur = = leftseparator) {separatorstack.push (cur);} else if (cur = = rightseparator) {if (!separat Orstack.isempty () && (SEPARATORSTACK.POP () = = Leftseparator)) {continue;} else {return false;}}} return Separatorstack.isempty ();} Private Innertoken Inner (Token prev) {//Store keys as normal Strings; we don ' t want keys to contain spans. StringBuilder sb = new StringBuilder ();//Consume the Left separator.consume (); char rightseparator = Getrightseparator (); while (Curchar! = Rightseparator && Curchar! = EOF) {sb.append (Curchar); consume ();}        if (Curchar = = EOF) {throw new IllegalArgumentException ("Missing closing separator");} Consume the right separator.consume (); if (sb.length () = = 0) {throw new IllegalStateException ("Disallow Empty content bet Ween separators,for Example {} ");} String key = Sb.tostring (); return new Innertoken (prev, key, Innercolor);} /** consumes and returns a token for a sequence of text. */private outertoken outer (Token prev) {int startIndex = Curcharindex;while (Curchar! = Getleftseparator () && CURC Har = EOF) {consume ();} return new Outertoken (prev, Curcharindex-startindex, OutercoloR);} /** * Consumes and returns a token representing, consecutive curly brackets. */private leftseparatortoken leftseparator (Token prev) {consume (); consume (); return new Leftseparatortoken (prev, Getleftseparator ());} /** Returns the next character in the input pattern without advancing. */private Char lookahead () {return Curcharindex < Pattern.length ()-1? Pattern.charat (Curcharindex + 1): EOF; /** * Advances the current character position without any error checking. * Consuming beyond the end of the string can only be happen if this parser * contains a bug. */private void Consume () {Curcharindex++;curchar = (Curcharindex = = Pattern.length ())? EOF:pattern.charAt (Curcharindex);} /** * Returns The raw pattern without expanding keys; Only useful for * debugging. Does not pass through to {@link #format ()} because doing so * would drop all spans. */@Overridepublic String toString () {return pattern.tostring ();} Private abstract Static class Token {Private final Token Prev;private token nExt;protected token (token prev) {This.prev = Prev;if (prev! = null) Prev.next = this;} /** Replace text in {@code target} with this token ' s associated value. */abstract void expand (Spannablestringbuilder target);/** Returns the number of characters after expansion. */abstract int getformattedlength ();/** Returns the character index after expansion.  */final int Getformattedstart () {if (prev = = null) {//the first Token.return 0;} else {//recursively ask the predecessor node for the starting Index.return Prev.getformattedstart () + Prev.getformattedlength ();}}} /** ordinary text between tokens.  */private Static class Outertoken extends token {private final int textlength;private int color;outertoken (Token prev, int textLength, int _color) {super (prev); this.textlength = Textlength;this.color = _color;} @Overridevoid expand (spannablestringbuilder target) {int startPoint = Getformattedstart (); int endPoint = StartPoint + Tex Tlength;target.setspan (new Foregroundcolorspan (color), StartPoint, ENDPOint, spannable.span_exclusive_exclusive);} @Overrideint Getformattedlength () {return textLength;}} /** A sequence of the curly brackets. */private Static class Leftseparatortoken extends Token {private char leftseparetor; Leftseparatortoken (Token prev, char _leftseparator) {super (prev); leftseparetor = _leftseparator;} @Overridevoid expand (spannablestringbuilder target) {int start = Getformattedstart (); Target.replace (start, start + 2, String.valueof (Leftseparetor));} @Overrideint getformattedlength () {//for Example,,replace "{{" with "{". return 1;}} private static class Innertoken extends Token {/** the InnerText without separators,like ' {' and '} '. */private final Stri ng Innertext;private int Color;innertoken (Token prev, String _inner, int _color) {super (prev); this.innertext = _inner;col or = _color;} @Overridevoid expand (spannablestringbuilder target) {int replacefrom = Getformattedstart ();//ADD 2 to account for the Sep Arators.int Replaceto = Replacefrom + innertext.length () + 2;TARGET.REPLAce (Replacefrom, Replaceto, InnerText); Target.setspan (new Foregroundcolorspan (color), Replacefrom, ReplaceTo-2, spannable.span_exclusive_exclusive);} @Overrideint getformattedlength () {///Note that value was only present after expand. Don ' t error check//because this is all//private Code.return innertext.length ();}}


OK, you need a demo friend please click here to download

[Android] is a gadget for textview with two-color text configuration Colorphrase

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.