Custom Controls for Android UI programming-highlighted TextView and androidtextview

Source: Internet
Author: User

Custom Controls for Android UI programming-highlighted TextView and androidtextview
Overview:

If you want to display a highlighted substring in a TextView. For example, I want to highlight "123456789" in "345. Note: Here I only highlight a part, not all. What do you do? I don't know if some beginners will think that, let these substrings segment different textviews and then process each TextView separately. Of course, if you are already a developer with some experience, I think you should not think about it again. Because Android has encapsulated -- SpannableStringBuilder for me. Next I will learn how to encapsulate some controls in Android to encapsulate a TextView (which can be set in xml or Java code ).


Instance:

There are actually two lighttextviews. The first is to match all mailboxes, and the second is to match all numbers. For details, you can download the source code at the end of the blog.



Instance features:

1. Set text content

2. Set the regular expression to be matched

3. Set the foreground color of the matched substring.

4. Set the background color of the matched substring.

5. Set whether to display the foreground color.

6. Set whether to display the background color.

7. Set whether to deploy the above settings


Example: 1. Set control properties in Java code

In fact, using Java code to set control attributes is undoubtedly simple. Because of this, you only need to encapsulate some available interfaces externally. For example:

/*** Set the background color * 2015-3-12 */private int mBackColor; public void setBackColor (int color) {mBackColor = color ;}
Is it easy?

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

Private void showForeBackground () {SpannableStringBuilder styleBuilder = new SpannableStringBuilder (mText); // wrap the font content if (mDecbackground) {for (int I = 0; I <matchedText. size (); I ++) {styleBuilder. setSpan (new BackgroundColorSpan (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 ForegroundColorSpan (mForeColor), matchedText. get (I ). getStart (), matchedText. get (I ). getEnd (), Spannable. SPAN_EXCLUSIVE_EXCLUSIVE) ;}} setText (styleBuilder );}
You may have guessed the function of this code segment when you see some variables and function names. It is the part that we need to highlight the sub-string. Here is a variable that requires attention to matchedText. Its definition in the Code is as follows:

private List<SubMatchModel> matchedText = null;
Yes. This is a List. What is the SubMatchModel in it? This is a self-encapsulated Model. Its function is to record the character set we encounter when matching strings (the current Model only records one subcharacter, so here it will be List ). Okay, now let's take a look at the content in 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 the matched subString

Start: start position of the substring.

End: the end position of the substring.


The following is a basic matching process and uses List <SubMatchModel> to record it:

/*** Obtain a substring matching regular expressions 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 it into a regular Matcher m; m = p. matcher (str); // obtain the Matched 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 ;}


Example:

private LightTextView mShowLightTextView = null;

Private void resetWidgets () {mShowLightTextView. setIsMatchOrNot (true); mShowLightTextView. setText ("my mailbox address is: abcdef@126.com, your mailbox address is: 123548@qq.com"); 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 this LigthTextView displayed? No, it only deploys some previous settings of LightTextView to this LightTextView.


2. Use of Custom Attributes attrs

After reading some attribute settings and deployment of LightTextView, does it feel a little complicated? Of course, there is no conflict between its complexity and the simple statement I mentioned earlier in Java, because there is no relationship between the two. If you have to talk about some relationships, I think it should be a balance between gains and losses. Just as if we want to write the program simply, the user may be more complicated. If we want to make the user easy to use, the program will use some complicated logic. This is also true here. If you want to make the external calls easier, the settings in it must be complicated. If you want to make the internal code simpler, the external content will be more complicated. So many times, what is the use of attrs?

For example, my code 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>


Note:

There are some points to note here.

1. Implement the following methods in the Java code constructor:

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);    }

The following example is called in the constructor:

public LightTextView(Context context, AttributeSet attrs) {        super(context, attrs);                TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.LightTextView);        init(mTypedArray);    }

2. the xml file must contain the program name:


Make sure that there are two parts framed in red above. Note that two parts are displayed in the red box. The former is the name of the custom property to be used after you, and the latter is the name of your current package, rather than the package where your custom control is located.


Download source code:

The above are all explanations. If you have any questions, please go to my source code address and download it.

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

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.