Custom controls for Android UI programming--textview that can be highlighted

Source: Internet
Author: User

Overview:

If you want to display a highlighted substring in a textview. For example, I want the "345" in "123456789" to be highlighted. Note that I'm referring to only one part of the highlight, not all of it. What would you do? I don't know if there's going to be some beginners will think of, let these substrings division in the different TextView, and then each textview separately processing. Of course, if you are already a developer with some experience, then I think you should stop thinking like that. Because, Android has already encapsulated the--spannablestringbuilder for me. Here I will learn some of the encapsulation of controls in Android to encapsulate one of our own TextView (either set in XML or set in Java code).


Example:

There are actually two lighttextview here. The first one is to match all the mailboxes and the second is to match all the numbers. Specific details, you can download the last source of the blog to view.



Example Function Description:

1. Setting text content

2. Set up regular expressions that need to be matched

3. Set the foreground color of the substring that matches

4. Set the background color of the substring that matches

5. Set whether the foreground color is displayed

6. Set whether the background color is displayed

7. Set whether the above settings are deployed


Examples of demonstration lectures:1. Implementing the settings of control properties in Java code

In fact, the use of Java code to set the properties of the control is undoubtedly simple. Because of it, it just needs to encapsulate some available interfaces externally. For example, this is the following:

/**     * Set Background color     * 2015-3-12 */    private int mbackcolor;    public void Setbackcolor (int color) {        Mbackcolor = color;    }
Isn't it simple?

Currently, Java code is much simpler in this respect than attrs. However, the key to the program is to rely on Java code to support. For example, the following code snippet:

private void Showforebackground () {        Spannablestringbuilder stylebuilder = new Spannablestringbuilder (mText); Package Font Contents                if (mdecbackground) {for            (int i = 0; i < matchedtext.size (); i++) {                Stylebuilder.setspan (new backgr Oundcolorspan (Mbackcolor), Matchedtext.get (i). Getstart (), Matchedtext.get (i). Getend (), spannable.span_exclusive_ EXCLUSIVE);            }        }                if (mdecforeground) {for            (int i = 0; i < matchedtext.size (); i++) {                Stylebuilder.setspan (new FOREGROUNDCOLORSP An (Mforecolor), Matchedtext.get (i). Getstart (), Matchedtext.get (i). Getend (), spannable.span_exclusive_exclusive);            }        }                SetText (Stylebuilder);    }
You might have guessed the functionality of the code snippet when you saw some variables and function names. It is the part that sets the highlight we need for the substring. Here is a variable that needs attention Matchedtext, which is defined in the code as follows:

Private list<submatchmodel> matchedtext = null;
Yes, this is a list, what is the Submatchmodel in it? This is a model that we have packaged ourselves. Its function is to record us in the process of matching strings, encountered the character set (the current model is only to record a sub-character, so this is the list). Well, now let's look at what's inside it:

public class Submatchmodel {    private String subString;        private int start;        private int end;    Public String getsubstring () {        return subString;    }    public void setsubstring (String subString) {        this.substring = subString;    }    public int Getstart () {        return start;    }    public void Setstart (int start) {        This.start = start;    }    public int getend () {        return end;    }    public void setend (int end) {        this.end = end;    }    }
There are only three member variables

SubString: Record substring to match

Start: The starting position of this substring

End: The ending position of this substring


The following is a basic matching procedure and uses list<submatchmodel> to record it:

/**     * Gets a substring that matches the regular character in a string     * @author Q-whai * 2015-3-12 * */public    static list<submatchmodel> Getmatchstring (String str, string exp) {        Pattern p = pattern.compile (exp);//here, compile into a regular        Matcher m;        m = P.matcher (str); Get matching        list<submatchmodel> models = new arraylist<submatchmodel> ();        Submatchmodel model = NULL;                while (M.find ()) {            model = new Submatchmodel ();                        Model.setsubstring (M.group ());            Model.setstart (M.start ());            Model.setend (M.end ());                        Models.add (model);        }                return models;    }


Use demonstration:

Private Lighttextview Mshowlighttextview = null;

private void Resetwidgets () {        mshowlighttextview.setismatchornot (true);        Mshowlighttextview.settext ("My email address is: [email protected], your e-mail address is: [email protected]");        Mshowlighttextview.setregularexp (Utils.getmatchemailstring ());        Mshowlighttextview.setbackcolor (Color.Blue);        Mshowlighttextview.setforecolor (color.red);        Mshowlighttextview.setdecbackground (true);        Mshowlighttextview.setdecforeground (true);        Mshowlighttextview.show ();    }
You can see the last method above, show (), is not showing this ligthtextview? No, it just deploys some of the previous settings for Lighttextview to this lighttextview.


2. Use of custom attribute Attrs

Looked at some of the above on the Lighttextview of the property settings and deployment, is it feeling a little complicated? Of course, it is not contradictory to say that it is complicated and that I said Java to write a simpler statement, because there is no relationship between the two. If there is to be some relationship, I think it should be a balance of gain and loss. Just as we are going to write the program simple, the user side may be more complex, if you want to make users easy to use, the program will be used in some of the more complex logic. This is also the case here. If you want to make the external call when it is relatively simple, then the inside of the setup is certainly more cumbersome, if you want to make the internal code simple, then the external content will be more cumbersome. Having said so much, what exactly is the use of attrs?

My code, for example, is like this:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Lighttextview" >        <attr name= "text" format= "string"/>        <attr name= "IsMatch" format= "boolean"/> <attr        name= "Decforeground" format= "boolean"/>        <attr name= "Decbackground" format= "boolean"/> <attr name=        " BackgroundColor "format=" Reference|color "/>        <attr name=" Foregroundcolor "format=" Reference|color "/>    </declare-styleable></resources>


Precautions :

Here are some places we need to pay attention to.

1. In the Java code constructor, implement the following methods:

private void init (TypedArray array) {        MText = array.getstring (r.styleable.lighttextview_text);        mismatch = Array.getboolean (R.styleable.lighttextview_ismatch, true);        Mdecforeground = Array.getboolean (R.styleable.lighttextview_decforeground, false);        Mdecbackground = Array.getboolean (R.styleable.lighttextview_decbackground, false);        Mforecolor = Array.getcolor (R.styleable.lighttextview_foregroundcolor, color.black);        Mbackcolor = Array.getcolor (R.styleable.lighttextview_backgroundcolor, Color.White);    }

To invoke the demo in the constructor:

Public Lighttextview (context context, AttributeSet Attrs) {        Super (context, attrs);                TypedArray Mtypedarray = context.obtainstyledattributes (Attrs, r.styleable.lighttextview);        Init (Mtypedarray);    }

2. You need to include the program name in the XML file:


Be sure to have the top two parts of the red box. It is also important to note that the two parts are framed in the red box. The former is the name of the custom attribute you want to use later, which is your current package name and cannot use the package that contains your custom control.


Source Download:

The above is the whole explanation, if you have anything not quite understand the place, welcome to my source address to download.

http://download.csdn.net/detail/u013761665/8496945

Custom controls for Android UI programming--textview that can be highlighted

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.