Complete Android expression function processing scheme _android

Source: Internet
Author: User
Tags delete key int size

An overview of Android expressive function processing scheme

1. Principle and Realization idea

2. Facial Image Display

3. Facial Expression Panel

4. Insert and delete the expression of the input box

5. Facial expression Add script

Android in the expression function, generally not with ImageView to set the picture to achieve, the expression will be nested in the text, then how to achieve it, here on the principle of which, in addition to the relevant functions of the implementation of ideas and specific code.

Let's take a look at the dynamic diagram of conscience

1. Principles and Ideas

A. Data format for expressive content
The expression looks like a picture, but in the data transmission is essentially a special text;
For example, QQ expression is a "/expression letter" structure, such as shy expression is/hx, bared teeth is/cy ... ;
Micro-Borrie expression is "[Expression name]" interface, such as cute expression is [cute] and so on ....

B. The principle of special text display pictures
need to use the spannablestring expansion of the Android string knowledge;
Spannablestring can allow a string of strings to be displayed, attaching a small piece of text to other content;
The expanded content of attachment may be a picture, or a text format, such as bold italic.

Below to expand the introduction of the next spannablestring, will be able to skip

The commonly used outreach content includes
Backgroundcolorspan background Color
Clickablespan text clickable, there are click events
Underlinespan Underline
Imagespan Pictures
Stylespan font style: bold, italic, etc.
Urlspan Text Hyperlink
In addition to the removal of lines, zoom size and other styles of expansion

Usage

spannablestring spannablestring = new spannablestring (source);
Imagespan span = new Imagespan (context, bitmap);
Spannablestring.setspan (span, start, start + Emojistr.length (), spannable.span_exclusive_exclusive);

Explain the following usage

First, wrap the original string into an expanded text spannablestring, and then create a span object that requires a type, such as a imagespan, and then using the Spannablestring Setspan method, Sets the span object to the corresponding position.
Start is the starting position of the content that needs to be attached
End is the starting position of the content that needs to be attached
flag Flag bit, here is the most commonly used exclusive_exclusive expression span extension text not included before and after,

In addition, there are inclusive meaning to be included.

For example, the original text is "the author is a good guy", then I create a bold expansion of the content, and to attach it to the author of the word to make it bold, the starting position is 2, that is, the third word, the end position is 4, that is, the fifth, and then according to the "Baotou not wrapping tail" principle, contains the third word does not contain the fifth word, That is to deal with the 34th two words "author", flag we set it to exclusive_inclusive that does not include the previous inclusion.

The final word is "the author is a good-looking guy."
If we enter content before attaching content and author two words, because is the exclusive does not contain, therefore does not follow the change
"Article Boredream author is a handsome guy"
If we enter content after attaching content and the author's word, the new content will contain the effect because it is inclusive included.
"The author of the article Boredream is a good-looking guy."

C. Matching of special text
know what special text to work with, how to deal with, there is a step is how to select the special text from a paragraph of text, that is, to get to the beginning and end of the special article, as well as his text content, here will be used to match to get the regular rules are not in detail, Introduction to the next expression here is a regular match.

2. Facial Image Display

Text attached to the expression picture is very simple, with the Imagespan in Spannablestring, the difficulty lies in the regular part of the acquisition process:

First is the regular writing, according to the need to write their own rules, here to the micro-blog expression For example String regex = "\\[[\u4e00-\u9fa5\\w]+\\]";

In brief, the outermost is the square bracket symbol, to note that because [] in the regular has special meaning, so need to use slash \ Escape (\ itself also need to escape so is two \), the Middle \u4e00-\u9fa5 Express Chinese,\\w to express the underlined any word character, + represents one or more, then this section is the text that matches one or more words and word characters within the square brackets.

Then go to the while loop match on it, use Matcher.find to get to the start of the match, as the start value of the Setspan, using the Matcher.group method to obtain the specific expression of the matching rules, The end value directly uses the start position plus the length of the expression text.

Put Code on

public static spannablestring Getemotioncontent (final context, final TextView TV, String source) {Spannablestr
 ing spannablestring = new spannablestring (source);

 Resources res = context.getresources ();
 String regexemotion = "\\[([\u4e00-\u9fa5\\w]) +\\]"; Pattern patternemotion = pattern.
 Compile (regexemotion);

 Matcher matcheremotion = Patternemotion.matcher (spannablestring);
  while (Matcheremotion.find ()) {//Get match to the specific character String key = Matcheremotion.group ();
  Match the start position of the string int start = Matcheremotion.start (); Use the expression name to get to the corresponding picture Integer imgres = emotionutils.
  Getimgbyname (key);
  if (imgres!= null) {//compress expression picture int size = (int) tv.gettextsize ();
  Bitmap Bitmap = Bitmapfactory.decoderesource (res, imgres);

  Bitmap Scalebitmap = Bitmap.createscaledbitmap (Bitmap, size, size, true);
  Imagespan span = new Imagespan (context, scalebitmap);
  Spannablestring.setspan (span, start, start + Key.length (), spannable.span_exclusive_exclusive); } return Spannablestring;

 }

The basic idea mentioned earlier, the picture processing place also need to explain the next

If you directly get the image of the resource file, it may be too large, so the method parameters in the need to display the text control, and then use the text size to the expression picture again compressed, which, Emotionutils class will not be introduced, which is a map set, key for the expression name, Value for the resid of the expression picture, and then provide a Getimgbyname method can be based on the name to get the picture key value to need to add more trouble, we will introduce an expression added script, easy to quickly import picture resources.

3. Facial Expression Panel

The structure is Viewpager provides multiple-page sliding, each page is a GridView display 20 expressions, at the end of a delete button;
The basic methods of using Viewpager and GridView are not introduced, and the special treatment is described here.

A. Size setting for each GridView
The GridView will display 3 rows of 7 columns, a total of 21 item, in order to make the item fit, the best way is to use dynamic calculation of the way to set wide, because the screen width is different, some other size calculation also need to pay attention to use DP value conversion to obtain the corresponding PX reuse, Ensure the suitability of the problem.

The idea is to get the screen width, minus the gap distance, then divide by 7 to calculate the width required for each item, then multiply by 3 plus the required clearance, calculate the height of the expression panel, and use the calculated value to create the Setup Panel size.

B. How many GridView are needed
How many pages are there, although the total number of expressions in most cases is fixed, but it is best to calculate how many pages are needed according to the code, rather than the direct person to visually calculate how many gridview.

The idea is for loop all the picture name, here use Map.keyset to get all the key sets, each cycle will add the picture name to a set, and then to judge, if full 20 as a group of expressions, a new GridView set up, Finally, all the expression-generated GridView is placed in a general view set, using Viewpager display.

C.gridview End Delete key processing
in the adapter and the Click event, use position to judge, if is the last one to carry on the special display and the click Processing.

These parts of the code is more messy, but there is no new knowledge point, are some logical aspects of content, do not post it.

4. Insert and delete the expression of the input box

In essence, the corresponding text data to operate, here the most attention is the input box in the cursor problem, the input box is actually a textview, display and the method described before, but dynamic additions and deletions need to pay attention to address the problem of location.

A. Manually set the cursor
Add a new expression, should be in the input box at the position of the current cursor inserted picture, so first know the location of the cursor to get here can use Et.setselectionstart method;
Also, after adding the expression, the cursor should be updated after the new additions, and the et.setselection (position) method will be used to set the cursor position.

B. Invoke System button event auto-process
Delete is relatively simple, here directly call the system's Delete button event, let a control Call button event method is Et.displatchkeyevent (new KeyEvent (Action, Code)); The action is action, with Action_down press action on it, and code for the button event code, delete corresponding is Keycode_del.

5. Facial expression Add script

Above, the knowledge point is all introduced complete, finally is the welfare time.

The expression is less then dozens of, many even hundred ~ one one according to the name sets corresponding the expression key value to be all sorts of pain, here recommends writes the script to handle, namely writes the section function to generate the necessary code automatically;

This paragraph is more flexible, need to write a script according to different needs, so the main is to provide a thought and then take micro-blog as an example to write code;

Micro-Blog expression is "[expression]", and the expression picture name is "d_ expression Pinyin" (in addition, there are other name styles, such as H_ or emoji_, etc., temporarily regardless of the principle of treatment);

Here to explain the premise, must be in accordance with certain rules to be able to do this semi-automatic processing, if the expression is simply the name is blind, it is out of line, if it is the company to do their own application, it is necessary to make the art of cutting map after the export of the picture file name according to the

Sina Weibo d_ expression Pinyin here are the corresponding Chinese pinyin instead of English, and the Chinese are and [expression] consistent, such as shy expression of the text is [shy], and the picture name is D_haixiu.

The micro Bo here to deal with it can follow the routine
1 Open the original microblogging client, all the expressions are selected, and then issued to
2 in the log to get this picture corresponding to the text data
3) using the expression rules to cycle the text to match
4 each time the cycle, the matching expression of the name into pinyin (pinyin4j and other tools)
5 translate the expression into pinyin and then spell the name of the picture resources (microblogging here is the addition of "D_" prefix)
6) Splicing Map.put code
7 after the loop completes, print out all the Map.put code, and then copy it into our Expression tool class using

With the code, the script creates a new Java project and runs it in the main function.

 public static void Weiboemoji () {StringBuilder sb = new StringBuilder (); String names = "[Ashamed sweet scented] [Meng god Olivia] [with Weibo to travel] [love red envelopes] [take photos] [success] →_→ [hehe] [haha] [love you] [dig nose excrement] [surprise] [Halo] [tear] [Chanzui] [mad] [hum] [lovely] [wrath] [Khan] [shy] [ sleep [money] [Steal a laugh] [laugh cry][doge][] [cool] [decline] [shut up] [despise] [heart] [applause] [sadness] [thinking] [sick] [kiss [Defy] [too happy] "+" [lazy to ignore you] [right hem] [left hem] [hush] [wronged] [vomit] [pitiful] [dozen breathe

 ] [winking] [disappointment] [top] [doubt] [trap] [Cold] [Goodbye] [black line] [sinister] [face] [dumbfounded] [Mutual powder] [heart] [sad] [pig] [panda] [rabbit] ";
 String Regexemoji = "\\[([\u4e00-\u9fa5a-za-z0-9]) +\\]"; Pattern Patternemoji = pattern.
 Compile (Regexemoji);

 Matcher Matcheremoji = patternemoji.matcher (names); Characterparser parser = Characterparser.
 GetInstance (); while (Matcheremoji.find ()) {//If you can match to string key = Matcheremoji.group ();//Get the specific character string pinyinname = "D_" +
  Parser.getspelling (key). replace ("[", ""). Replace ("]", "");
 Sb.append ("Emojimap.put" + key + "\", r.drawable. "+ Pinyinname +"); \ n "); } System.
Out.println (Sb.tostring ()); }

Run the results, paste from the console copy code into the tool class in the project

Maybe some of the expression file name is not according to the routine, for example, Sina Weibo here laugh cry expression, the text is [laugh cry], and picture file name is D_xiaoku, then also does not matter, you copy to the project, if the picture resources match not on the words also will error prompt, corresponding modification can be.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.