Android Imitation Sina Weibo, QQ space and other posts display (2) _android

Source: Internet
Author: User

First, introduce

This is a post on Sina Weibo, just including the topic, expression, @ Friends three display. The display method has been elaborated in the previous article, which uses spannablestring. This article mainly introduces the Analytic tool class that displays this kind of post.

Second, realize

1. String representations and corresponding regular expressions

The topic uses # #号括起来
expression expressed by []
@ Friend Nickname
The use of regular matching to resolve the post information.

Topic-> #[^#]+#
Expression-> [[^]]+]
@ friend-> @ Buddy Nickname

2. Write a common method for spanablestring to make regular judgments, if the requirements, the content will change color

private static void Dealpattern (int color, spannablestring spannablestring, Pattern patten, int start) throws Exception { C1/>matcher Matcher = Patten.matcher (spannablestring);
  while (Matcher.find ()) {
   String key = Matcher.group ();
   The text that returns the index of the first character matches the entire regular expression, and ture continues recursively
   if (Matcher.start () < start) {
    continue;
   }
   Calculates the length of the content, which is the length of the string to be replaced
   int end = Matcher.start () + key.length ();
   Sets the foreground color SPAN
   spannablestring.setspan (new Foregroundcolorspan (color), Matcher.start (), End, Spannable.span_ exclusive_exclusive);
   if (End < Spannablestring.length ()) {
    //If the entire string has not been validated, continue ...
    Dealpattern (color, spannablestring, Patten, end);
   }
   break;
  }
 }

3. Some are clickable, so you need a way to handle clickable content

① first defines an interface and passes the click event to the caller via an interface

 public interface spanclicklistener<t>{
  void Onspanclick (t);
 }

② writes a common method, makes a regular judgment of spanablestring, and if it meets the requirements, sets the content to be clicked

private static void Dealclick (Spannablestring spannablestring, Pattern patten, int start, final Spanclicklistener spancli
  Cklistener, Final Object Bean) {Matcher Matcher = Patten.matcher (spannablestring);
   while (Matcher.find ()) {String key = Matcher.group ();
   The text that returns the index of the first character matches the entire regular expression, and ture continues recursively if (Matcher.start () < start) {continue;
   //Calculates the length of the content, that is, the length of the string to be replaced int end = Matcher.start () + key.length (); Spannablestring.setspan (New Clickablespan () {@Override public void OnClick (View widget) {Spanclicklistener.
    Onspanclick (Bean);
     @Override public void Updatedrawstate (Textpaint ds) {super.updatedrawstate (DS);
   Set Brush Property Ds.setunderlinetext (FALSE);//Default Underline}}, Matcher.start (), end, spannable.span_exclusive_exclusive);
    if (End < Spannablestring.length ()) {//If the entire string has not been validated, continue ...
   Dealclick (Spannablestring, Patten, end, Spanclicklistener, Bean);
  } break;

 }
 }

4. Facial expression Resolution (write an expression later)

private void Dealexpression (context, spannablestring spannablestring, Patten, int start) throws exc
  eption {Matcher Matcher = Patten.matcher (spannablestring);
   while (Matcher.find ()) {String key = Matcher.group ();
   if (Matcher.start () < start) {continue;
   String value = Emojimap.get (key);
   if (Textutils.isempty (value)) {continue; ///Generate Picture resource id int resid = context.getresources () by matching the string above. Getidentifier (Value, "drawable", Context.getpacka
   Gename ());
    if (resid!= 0) {drawable emoji = context.getresources (). getdrawable (RESID);
    int w = (int) (Emoji.getintrinsicwidth () * 0.40);
    int h = (int) (Emoji.getintrinsicheight () * 0.40);
    Emoji.setbounds (0, 0, W, h);
    Through the image resource ID to get bitmap, with a imagespan to wrap imagespan Imagespan = new Imagespan (emoji);
    Calculates the length of the name of the picture, which is the length of the string to be replaced int end = Matcher.start () + key.length (); Replaces the picture in the specified position in the string Spannablestring.setspan (Imagespan, Matcher.start (), End, spannable.span_inclusive_exclusive);
    if (End < Spannablestring.length ()) {dealexpression (context, spannablestring, Patten, end);
   } break;

 }
  }
 }

5. Keyword Color treatment method, the actual use of scenes such as map keyword search, matching to the keyword address keyword display special color

public static spannablestring getkeywordspan (int color, string str, String patterstr) throws Exception {
  spannablestr ing spannablestring = new spannablestring (str);
  Pattern Patten = Pattern.compile (Patterstr, pattern.case_insensitive);
  Dealpattern (color, spannablestring, Patten, 0);
  return spannablestring;
 }

6. The topic processing, the parameter needs to pass on the topic object. This only deals with a single topic in one post.

 public static spannablestring gettopicspan (int color, String str, Boolean Clickable,spanclicklistener Spanclicklistener , Topic Topic) throws Exception {
  spannablestring spannablestring = new spannablestring (str);
  Pattern Patten = Pattern.compile (Patternstring.topic_pattern, pattern.case_insensitive);
  if (clickable) {
   Dealclick (spannablestring, Patten, 0, Spanclicklistener, topic);
  }
  Dealpattern (color, spannablestring, Patten, 0);
  return spannablestring;
 }

7.@ buddy processing, parameters need to pass in @ Friend list

public static spannablestring getatuserspan (int color, String str, Boolean clickable, Spanclicklistener Spanclicklistener, list<user> atusers) throws Exception {spannablestring
  spannablestring = new Spannablestring (str);
  Pattern Patten;
  for (User u:atusers) {
   Patten = Pattern.compile ("@" + u.getname (), pattern.case_insensitive);
   if (clickable) {
    Dealclick (spannablestring, Patten, 0, Spanclicklistener, u);
   }
   Dealpattern (color, spannablestring, Patten, 0);
  }
  return spannablestring;
 }

8. Facial expression processing, so concise

 public static spannablestring Getexpressionspan (context, String str) throws Exception {return
  Expressionconvertutil.getinstace (). getexpressionstring (context, str);
 

Third, the use

1. Keyword discoloration

private void Testcoloredkeywd () {
  string = "Android" means "robot", also Google on November 5, 2007, Android logo related pictures, Android logo related pictures (36) \ n ";
  Spannablestring cardtext = null;
  try {
   cardtext = Spanutils.getkeywordspan (Getresources (). GetColor (r.color.md_green_600), String, "Android");
  catch (Exception e) {
   e.printstacktrace ();
  }
  Tvcoloredkeywd.settext (Cardtext);
 }

2. Topic testing, it is important to note that some of the content can be clicked to set Tvtopic.setmovementmethod (Linkmovementmethod.getinstance ()), otherwise click No effect

private void Testtopic () {
  String topic = "#舌尖上的大连 # Four kinds of gold grilled cheese to eat cheese-loving tub friends do not miss the ~l second shot video \ n";
  Spannablestring topictext = null;
  try {
   topictext = Spanutils.gettopicspan (Color.Blue, topic, True, new spanutils.spanclicklistener<topic> () {
    @Override public
    void Onspanclick (Topic t) {
     toast.maketext (mainactivity.this, "click topic:" + t.tostring (), Toast.length_short), show ();
    }
   , New Topic (1, "Dalian on the tip of the Tongue"));
  catch (Exception e) {
   e.printstacktrace ();
  }
  Tvtopic.settext (topictext);
  If you want to implement a click, you must set this
  Tvtopic.setmovementmethod (Linkmovementmethod.getinstance ());
 }

3.@ Friend Test

private void Textatusers () {
  list<user> users = new arraylist<> ();
  Users.add (New User (1, "Buddy 1"));
  Users.add (New User (2, "Buddy 2"));
  StringBuilder sb = new StringBuilder ("Come Look at it");
  for (User u:users) {
   sb.append ("@"). Append (U.getname ());
  }
  Sb.append ("\ n");
  try {
   spannablestring Atspan = Spanutils.getatuserspan (Color.Blue, sb.tostring (), True, new Spanutils.spanclicklistener<user> () {
    @Override public
    void Onspanclick (user user) {
     Toast.maketext (Mainactivity.this, "@ Buddy:" + user.tostring (), Toast.length_short). Show ();
    }
   , users;

   Tvtestat.settext (Atspan);
   Tvtestat.setmovementmethod (Linkmovementmethod.getinstance ());
  } catch (Exception e) {
   e.printstacktrace ();
  }

 }

4. Facial expression Test

 private void Textexpression () {
  String exstr = "The weather is very good today [bared teeth], is not supposed to do something [color]";
  Spannablestring span = null;
  try {
   span = Spanutils.getexpressionspan (this, exstr);
  } catch (Exception e) {
   e.printstacktrace ();
  }
  Tvexpression.settext (span);
 }

Effect chart

Download: Https://github.com/LineChen/SpannableStringDemo

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.