Implementation of the expression function of the android Sina Weibo Client

Source: Internet
Author: User
Tags xml reader

This is a good article. I transfer it to my favorites. The highest level of technology is sharing.

 

I have been engaged in the android Sina Weibo client recently and have some experiences with it.
The following ideas can be used to get the expression function of the android client:
1. The homepage downloads Sina's emoticons to a local folder. The emoticons are named after the emoticons of Sina Weibo.
For example, if shame.gif is the shame of Sina, you can also name it as shame.gif. The same name is mainly used to match the corresponding code of the expression.
2. Put all local expressions in the android resource file ---- drawable
3. access Sina's emoticons interface (SINA returns two types of data: JSON and XML, I use XML) to store the returned information parsed by the XML parser in an emotion. java Bean. the Java code finds the corresponding resource emoticons one by one.
4. Implement an emoticon interface that can be selected by the user, which is implemented by using the gridview.
5. click each item in the gridview, process the corresponding emoticon code based on the index of the item, and then convert the code to the corresponding emoticon image using the regular expression, insert edittext into the final expression to send the message.

 

The specific implementation process is as follows:
1. The implementation of downloading Sina emoticons to a local machine is as follows: (you can create a Java project to download it)
Public void getfriendlist () throws exception {blogreleaseserviceimpl service = new blogreleaseserviceimpl (); List <emotions> List = service. getemotion (); For (emotions: List) {string Path = emotions. geturl (); string filename = path. substring (path. lastindexof ("/") + 1, path. length (); Url url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setrequestmethod (" Get "); Conn. setreadtimeout (5*1000); If (Conn. getresponsecode () == 200) {inputstream is = Conn. getinputstream (); byte [] DATA = readstream (is); file = new file ("F: \ sina_images \" + filename ); fileoutputstream FS = new fileoutputstream (File); FS. write (data); FS. close ();} else {system. out. println ("request failed") ;}} public byte [] readstream (inputstream is) throws exception {bytearrayoutputstream OS = new bytearr Ayoutputstream (); byte [] buffer = new byte [2048]; int Len = 0; while (LEN = is. Read (buffer ))! =-1) {OS. Write (buffer, 0, Len);} is. Close (); Return OS. tobytearray ();}
2: Put the local expressions in the android resource file ---- drawable (this is not to be said, just select all the files to copy. 1. Access Sina's emoticons interface and return the following information:
<Emotion> <phrase> [Xi] </phrase> <type> face </type> <URL> http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/c2/tooth.gif </URL> <is_hot> false </is_hot> <is_common> true </is_common> <order_number> 0 </order_number> <Category> </emotion>
3.2 is stored in an emotion. Java file. The emotion. Java code is as follows:
Package COM. UIM. microblog. model; import Java. io. serializable; public class emotions implements serializable {/***/Private Static final long serialversionuid = 1l; private string phrase; // Replace the text private string type with emoticon; private string URL; // the position where the emoticon image is stored. Private string ishot; // whether it is a popular emoticon private string iscommon; // whether it belongs to a general private string ordernumber; // Private string category; // Private string imagename; // Public String getimagename () {return imagename ;} public void setimagename (string imagename) {This. imagename = imagename;} Public String getphrase () {return phrase;} public void setphrase (string phrase) {This. phrase = phrase;} Public String GetType () {return type;} public void settype (string type) {This. type = type;} Public String geturl () {return URL;} public void seturl (string URL) {This. url = URL;} Public String getishot () {return ishot;} public void setishot (string ishot) {This. ishot = ishot;} Public String getiscommon () {return iscommon;} public void setiscommon (string iscommon) {This. iscommon = iscommon;} Public String getordernumber () {return ordernumber;} public void setordernumber (string ordernumber) {This. ordernumber = ordernumber;} Public String getcategory () {return category;} public void setcategory (string category) {This. category = category ;}}

 

3.2 is stored in an emotion. Java file. The emotion. Java code is as follows:

 

Package com.uim.microblog.net. handler; import Java. util. arraylist; import Java. util. list; import Org. XML. sax. attributes; import Org. XML. sax. saxexception; import Org. XML. sax. helpers. defaulthandler; import COM. UIM. microblog. model. emotions; import COM. UIM. microblog. model. responseresult; public class blogemotionshandler extends defaulthandler {private list <emotions> list; private emotions; private respo Nseresult responseresult; private string tag = NULL; // The resolved element public list <emotions> getemotionslist () {return list ;}@ overridepublic void characters (char [] CH, int start, int length) throws saxexception {If (tag! = NULL) {string textarea = new string (CH, start, length);/** start parsing expression data */If ("phrase ". equals (TAG) {emotions. setphrase (textarea);} else if ("type ". equals (TAG) {emotions. settype (textarea);} else if ("url ". equals (TAG) {try {emotions. seturl (textarea); string imagename = textarea. substring (textarea. lastindexof ("/") + 1, textarea. length ()-4); emotions. setimagename (imagename);} catch (exception e) {e. printstacktrace () ;}} else if ("is_hot ". equals (TAG) {emotions. setishot (textarea);} else if ("is_common ". equals (TAG) {emotions. setiscommon (textarea);} else if ("order_number ". equals (TAG) {emotions. setordernumber (textarea);} else if ("category ". equals (TAG) {emotions. setcategory (textarea);} else if ("retn ". equals (TAG) {responseresult. setretn (textarea);} else if ("DESC ". equals (TAG) {responseresult. setdesc (textarea) ;}}@ overridepublic void enddocument () throws saxexception {super. enddocument () ;}@ overridepublic void endelement (string Uri, string localname, string QNAME) throws saxexception {tag = NULL; If ("MB ". equals (localname) {} else if ("emotions ". equals (localname) {responseresult = NULL;} else if ("Emotion ". equals (localname) {list. add (emotions); emotions = NULL ;}@ overridepublic void startdocument () throws saxexception {list = new arraylist <emotions> () ;}@ overridepublic void startelement (string Uri, string localname, string QNAME, attributes) throws saxexception {If ("MB ". equals (localname) {responseresult = new responseresult ();} else if ("emotions ". equals (localname) {} else if ("Emotion ". equals (localname) {emotions = new emotions () ;}tag = localname ;}}
3.4sax Parsing
Public list <emotions> getemotion () {bloggetdata getdata = new bloggetdata (); string result = getdata. blogemotionsservlet (); try {// generate the sax parsing object parser = saxparserfactory. newinstance (). newsaxparser (); // generate xml reader = parser. getxmlreader (); blogemotionshandler handler = new blogemotionshandler (); // set handlerreader. setcontenthandler (handler); // specify the file to parse the reader. parse (New inputsource (New stringreader (result); // obtain the list <emotions> emotionlist = handler. getemotionslist ();} catch (parserconfigurationexception e) {e. printstacktrace ();} catch (saxexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} return emotionlist ;}
4: 4. 1 implement the expression selector --- gridview

 

<GridViewandroid:id="@+id/blog_sendmsg_gvemotion"android:layout_width="fill_parent"android:layout_height="150sp"android:scrollbars="vertical"android:numColumns="auto_fit"android:verticalSpacing="15dp"android:background="@color/blog_list_back"android:stretchMode="columnWidth"android:gravity="center"android:visibility="gone"android:columnWidth="40dp"></GridView>
4.2 items in the gridview ----- gridview_emotion_item.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent">  <ImageView  android:id="@+id/blog_sendmsg_emotion"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_weight="50"  android:layout_gravity="center">  </ImageView></LinearLayout>
4.3 load the emoticon image to the gridview for display
Public void addexpression (view) {If (expressiongriview. getvisibility () = view. gone) {expressiongriview. setvisibility (view. visible); emotionlist = bloghomeactivity. emotions; arraylist 5: click every item in the gridview, process the corresponding emoticon code based on the index of the item, and then convert the code to the corresponding emoticon image using the regular expression, insert edittext into the final expression to send the 5.1: code to the image:

 

public SpannableString txtToImg(String content){SpannableString ss = new SpannableString(content);int starts = 0;int end = 0;if(content.indexOf("[", starts) != -1 && content.indexOf("]", end) != -1){starts = content.indexOf("[", starts);end = content.indexOf("]", end);String phrase = content.substring(starts,end + 1);String imageName = "";List<Emotions> list = BlogHomeActivity.emotions;for (Emotions emotions : list) {if (emotions.getPhrase().equals(phrase)) {imageName = emotions.getImageName();}}try {Field f = (Field)R.drawable.class.getDeclaredField(imageName);int i= f.getInt(R.drawable.class);Drawable drawable = BlogSendMsgActivity.this.getResources().getDrawable(i);  if (drawable != null) {drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());         ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);          ss.setSpan(span, starts,end + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  }} catch (SecurityException e) {e.printStackTrace();} catch (NoSuchFieldException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {}}return ss;}

 

5.2: insert edittext
Emtions = emotionlist. get (position); // get the expression bean int cursor = etcontent. getselectionstart (); etcontent. gettext (). insert (cursor, txttoimg (emtions. getphrase ()));

 

After finishing the work, give:

 

From: http://jspjson.iteye.com/blog/1109222

 

Author: yiyaaixuexi published on 22:57:33 Original article link Read: 414 comment: 1 view comment

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.