Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/38498353, this article from: "Zhang Hongyang's Blog"
Today saw an iOS written by the Turing machine, directly to the official website (http://www.tuling123.com/openapi/) See the next API access, too simple, just a GET request ~ So, wrote a android version of the robot, no technical content, But very fun ~ just last night to see their favorite Qin Moon, Hey, little Pixiu, is my robot pet ~
1.
First Look at:
Of course not only the small talk, but also the more powerful, see:
Well, first of all, interested in the study, but also support automatic learning Oh ~
The code starts here ~
2. layout file
The display of the main interface message is a ListView, but the item in this ListView has two styles, one is the green message on the left and the other is the white message on the right.
Message layout file on the left:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:orientation=" vertical " > <textview android:id= "@+id/chat_from_createdate" android:layout_width= "Wrap_content" Andro id:layout_height= "Wrap_content" android:text= "2012-09-01 18:30:20" style= "@style/chat_date_style"/> ; <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:orie ntation= "Horizontal" > <linearlayout android:layout_width= "wrap_content" android:layout _height= "Wrap_content" android:layout_marginleft= "10DP" android:orientation= "vertical" > <imageview android:id= "@+id/chat_from_icon" android:layout_width= "49DP" android:layout_height= "49DP" android:src= "@drawable/icon"/> <textview android:id= "@+id/chat_from_name" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android oid:layout_gravity= "center" android:text= "small Xiu ghpd Xiu ghpd" android:textsize= "18sp"/> </lin earlayout> <textview android:id= "@+id/chat_from_content" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:minheight= "50DP" Android:back ground= "@drawable/chat_from_msg" android:text= "big ... "Android:textsize=" 18sp "android:textcolor=" #000 "android:gravity=" center_vertical " Android:focusable= "true" android:clickable= "true" android:linespacingextra= "2DP"/ > </LinearLayout></LinearLayout>
The right side and the left are basically the same, not posted, and finally the code is given.
Main layout file:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:background=" @drawable/C Hat_bg_default "android:orientation=" vertical "> <relativelayout android:id=" @+id/ly_chat_title " Android:layout_width= "Fill_parent" android:layout_height= "45DP" android:background= "@drawable/title_bar" &G T <textview android:layout_width= "fill_parent" android:layout_height= "Fill_parent" Andro id:gravity= "center" android:text= "small Pixiu" android:textcolor= "#fff" android:textsize= "20SP" android:textstyle= "Bold"/> </RelativeLayout> <relativelayout android:id= "@+id/ly_chat_ Bottom "android:layout_width=" fill_parent "android:layout_height=" 55DP "Android:layout_alignparentbot Tom= "true" Android:background= "@drawable/bottom_bar" > <button android:id= "@+id/id_chat_send" android:l Ayout_width= "60DP" android:layout_height= "40DP" android:layout_alignparentright= "true" an Droid:layout_centervertical= "true" android:layout_marginright= "10DP" android:background= "@drawable/C Hat_send_btn "android:onclick=" SendMessage "android:text=" send "/> <edittext a Ndroid:id= "@+id/id_chat_msg" android:layout_width= "fill_parent" android:layout_height= "40DP" Android:layout_centervertical= "true" android:layout_marginleft= "10DP" android:layout_marginright = "10DP" android:layout_toleftof= "@id/id_chat_send" android:background= "@drawable/login_edit_normal" Android:singleline= "true" android:textsize= "18sp"/> </RelativeLayout> <listview Android:id= "@+id/iD_chat_listview "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "android:layou T_above= "@id/ly_chat_bottom" android:layout_below= "@id/ly_chat_title" android:cachecolorhint= "#0000" Android:divider= "@null" android:dividerheight= "5DP" android:scrollbarstyle= "Outsideoverlay" > </Lis Tview></relativelayout>
It's the ListView and the message box and the message button.
3, Httputils
Encapsulates a tool class for accessing the API, in fact a GET request:
Package Com.zhy.utils;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import java.io.InputStream; Import Java.io.unsupportedencodingexception;import Java.net.httpurlconnection;import Java.net.URL;import Java.net.urlencoder;import Java.util.date;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;import Com.example.android_robot_01.bean.commonexception;import Com.example.android_robot_01.bean. Result;import Com.google.gson.gson;public class Httputils{private static String Api_key = " 534dc342ad15885dffc10d7b5f813451 ";p rivate static String URL =" Http://www.tuling123.com/openapi/api ";/** * sends a message, And get the message returned * @param msg * @return */public static chatmessage sendmsg (String msg) {chatmessage message = new Chatmessage (); String url = setparams (msg); String res = doget (URL); Gson Gson = new Gson (); result = Gson.fromjson (res, result.class); if (Result.getcode () > 400000 | | result.gettext () = = null| | result.get Text (). trIm (). Equals ("")) {message.setmsg ("The feature waits for development ...");} Else{message.setmsg (Result.gettext ());} Message.settype (Type.input); Message.setdate (new Date ()); return message;} /** * Stitching URL * @param msg * @return */private static string SetParams (String msg) {try{msg = Urlencoder.encode (msg, "UTF-8") ;} catch (Unsupportedencodingexception e) {e.printstacktrace ();} return URL + "? key=" + Api_key + "&info=" + msg;} /** * GET request, get return data * @param urlstr * @return */private static string doget (String urlstr) {URL url = null; HttpURLConnection conn = Null;inputstream is = null; Bytearrayoutputstream BAOs = null;try{url = new URL (urlstr); conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (5 *), Conn.setconnecttimeout (5 *), Conn.setrequestmethod ("GET"); Conn.getresponsecode () = = () {is = Conn.getinputstream (); BAOs = new Bytearrayoutputstream (); int len = -1;byte[] buf = new Byte[128];while (len = Is.read (BUF))! =-1) {baos.write (buf, 0, Len);} Baos.flush (); return baos.tostring ();} Else{throw NEW commonexception ("Server connection Error! ");}} catch (Exception e) {e.printstacktrace (); throw new Commonexception ("Server connection Error! ");} Finally{try{if (is! = null) Is.close ();} catch (IOException e) {e.printstacktrace ();} Try{if (BAOs! = null) Baos.close ();} catch (IOException e) {e.printstacktrace ();} Conn.disconnect ();}}}
Exposed, is sendmsg this static method, of course, the returned data is also directly encapsulated into the Chatmessage
4, Chatmessage
package com.example.android_robot_01.bean;import Java.text.dateformat;import Java.text.simpledateformat;import Java.util.date;public class chatmessage{/** * Message type */private type type;/** * message Content */pri Vate string msg;/** * Date */private Date date;/** * Date strings format */private string datestr;/** * Sender */private string name;publi c enum Type{input, Output}public chatmessage () {}public chatmessage (type type, String msg) {super (); this.type = Type; This.msg = msg;setdate (New Date ());} Public String Getdatestr () {return datestr;} Public Date getDate () {return date;} public void SetDate (date date) {this.date = Date;dateformat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); this.datestr = Df.format (date);} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public type GetType () {return type;} public void SetType (type type) {This.type = type;} Public String getmsg () {return msg;} public void Setmsg (String msg) {this.msg = msg;}}
It's so simple.
5. Main activity
Package Com.example.android_robot_01;import Java.util.arraylist;import Java.util.date;import java.util.List;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.text.textutils;import Android.view.view;import Android.view.Window;import Android.view.inputmethod.inputmethodmanager;import Android.widget.edittext;import Android.widget.ListView;import Android.widget.toast;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;import Com.zhy.utils.httputils;public class Mainactivity extends activity{/** * Display a ListView of messages */ Private ListView mchatview;/** * Text field */private EditText mmsg;/** * Store Chat message */private list<chatmessage> mdatas = new A Rraylist<chatmessage> ();/** * Adapter */private chatmessageadapter madapter;private Handler mhandler = new Handler () { public void Handlemessage (Android.os.Message msg) {Chatmessage from = (chatmessage) msG.obj;mdatas.add (from); madapter.notifydatasetchanged (); Mchatview.setselection (Mdatas.size ()-1);};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.main_chatting); InitView (); mAdapter = new Chatmessageadapter (this, mdatas); Mchatview.setadapter (Madapter);} private void Initview () {Mchatview = (ListView) Findviewbyid (r.id.id_chat_listview); mmsg = (EditText) Findviewbyid ( R.ID.ID_CHAT_MSG) Mdatas.add (New Chatmessage (Type.input, "I am a small Xiu ghpd Xiu Ghpd, glad to serve You")); public void SendMessage (view view) {final String msg = Mmsg.gettext (). toString (); if (Textutils.isempty (msg)) { Toast.maketext (This, "you haven't filled in information yet ...", Toast.length_short). Show (); return;} Chatmessage to = new Chatmessage (Type.output, msg); To.setdate (new Date ()); Mdatas.add (to); Madapter.notifydatasetchanged (); Mchatview.setselection (Mdatas.size ()-1); Mmsg.settext ("");// Off soft keyboard Inputmethodmanager IMM = (inputmethodmanager) getsystemservice (Context. Input_method_service)///Get Inputmethodmanager instance if (Imm.isactive ()) {//If Imm.togglesoftinput is turned on ( Inputmethodmanager.show_implicit,inputmethodmanager.hide_not_always)///Turn off the soft keyboard and turn on the same method, this method is switched on and off state}new Thread ( {public void Run () {Chatmessage from = Null;try{from = Httputils.sendmsg (msg),} catch (Exception e) {from = new chatmessage (Type.input, "The server hangs up ..."); Message message = Message.obtain (); message.obj = from;mhandler.sendmessage (message);};}. Start ();}}
Set the data for the ListView, set the first sentence at the beginning "I am a small Xiu ghpd Xiu GHPD, I am glad to serve you"; there is Sendbutton event handling.
6. Adapter
Package Com.example.android_robot_01;import Java.util.list;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;import Com.example.android_robot_01.bean. Chatmessage;import Com.example.android_robot_01.bean. Chatmessage.type;public class Chatmessageadapter extends Baseadapter{private layoutinflater minflater;private List <ChatMessage> Mdatas;public Chatmessageadapter (context context, list<chatmessage> datas) {minflater = Layoutinflater.from (context); mdatas = Datas;} @Overridepublic int GetCount () {return mdatas.size ();} @Overridepublic Object getItem (int position) {return mdatas.get (position);} @Overridepublic long Getitemid (int position) {return position;} /** * Accept message 1, send message 0 */@Overridepublic int getitemviewtype (int position) {Chatmessage msg = mdatas.get (position); return Msg.gettype () = = Type.input? 1:0;} @Overridepublic int Getviewtypecount () {return 2;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Chatmessage chatmessage = Mdatas.get ( position); Viewholder Viewholder = null;if (Convertview = = null) {Viewholder = new Viewholder (); if (chatmessage.gettype () = = Type.INPU T) {Convertview = Minflater.inflate (r.layout.main_chat_from_msg,parent, false); viewholder.createdate = (TextView) Convertview.findviewbyid (r.id.chat_from_createdate); viewholder.content = (TextView) Convertview.findviewbyid ( r.id.chat_from_content); Convertview.settag (Viewholder);} Else{convertview = Minflater.inflate (r.layout.main_chat_send_msg,null); viewholder.createdate = (TextView) Convertview.findviewbyid (r.id.chat_send_createdate); viewholder.content = (TextView) Convertview.findviewbyid ( r.id.chat_send_content); Convertview.settag (Viewholder);}} Else{viewholder = (Viewholder) Convertview.gettag ();} ViewHolder.content.setText (Chatmessage.getmsg ()); ViewHolder.createDate.setText (Chatmessage.getdatestr ()); return Convertview;} Private Class VieWholder{public TextView createdate;public TextView name;public TextView content;}}
The only thing to note is that since our ListView item has two display styles, we need to rewrite two more methods than usual:
/** * Accept message 1, send message 0 */@Overridepublic int getitemviewtype (int position) {Chatmessage msg = mdatas.get (position); return Msg.gettype () = = Type.input? 1:0;} @Overridepublic int Getviewtypecount () {return 2;}
Getviewtypecount return is the number of species, getitemviewtype according to the position of course the decision to return different integer variables. Then, in GetView, load different item layouts based on the type of message.
Basically also finished, no technical content, purely entertainment, you program ape brother, nothing can take a little time to write down play a Play ~ rest ~
SOURCE Click to download