原文转自:http://blog.csdn.net/lmj623565791/article/details/38498353



今天看到一个ios写的图灵机器人,直接去官网(http://www.tuling123.com/openapi/)看了下API接入,太简单了,就一个get请求~于是乎,写了一个Android版本的机器人,没什么技术含量,但是挺好玩的~刚好昨晚看了自己喜欢的秦时明月,嘿嘿,小貔貅,就是我的机器人宠物啦~

1、效果图

先看看效果图:


当然不仅是闲聊,还有更强大的,见下图:


好了,效果图就先这样了,有兴趣的自己去研究下,还支持自动学习噢 ~

下面开始代码了~

2、布局文件

主界面消息的显示是一个ListView,不过这个listView中的Item有两种风格,一个是左边的绿色消息,一个是右边的白色消息

左边的消息布局文件:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/chat_from_createDate"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="2012-09-01 18:30:20"  
  12.         style="@style/chat_date_style"  
  13.        />  
  14.   
  15.     <LinearLayout  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:orientation="horizontal" >  
  19.   
  20.         <LinearLayout  
  21.             android:layout_width="wrap_content"  
  22.             android:layout_height="wrap_content"  
  23.             android:layout_marginLeft="10dp"  
  24.             android:orientation="vertical" >  
  25.   
  26.             <ImageView  
  27.                 android:id="@+id/chat_from_icon"  
  28.                 android:layout_width="49dp"  
  29.                 android:layout_height="49dp"  
  30.                 android:src="@drawable/icon" />  
  31.   
  32.             <TextView  
  33.                 android:id="@+id/chat_from_name"  
  34.                 android:layout_width="wrap_content"  
  35.                 android:layout_height="wrap_content"  
  36.                 android:layout_gravity="center"  
  37.                 android:text="小貅貅"  
  38.                 android:textSize="18sp" />  
  39.         LinearLayout>  
  40.           
  41.         <TextView   
  42.             android:id="@+id/chat_from_content"  
  43.             android:layout_width="wrap_content"  
  44.             android:layout_height="wrap_content"  
  45.             android:minHeight="50dp"  
  46.             android:background="@drawable/chat_from_msg"  
  47.             android:text="有大吗。。。"  
  48.             android:textSize="18sp"  
  49.             android:textColor="#000"  
  50.             android:gravity="center_vertical"  
  51.             android:focusable="true"  
  52.             android:clickable="true"  
  53.             android:lineSpacingExtra="2dp"  
  54.             />  
  55.     LinearLayout>  
  56.   
  57. LinearLayout>  

右边的和左边基本一致,就不贴了,最后会给出代码。

主布局文件:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="@drawable/chat_bg_default"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <RelativeLayout  
  9.         android:id="@+id/ly_chat_title"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="45dp"  
  12.         android:background="@drawable/title_bar" >  
  13.   
  14.         <TextView  
  15.             android:layout_width="fill_parent"  
  16.             android:layout_height="fill_parent"  
  17.             android:gravity="center"  
  18.             android:text="小貔貅"  
  19.             android:textColor="#fff"  
  20.             android:textSize="20sp"  
  21.             android:textStyle="bold" />  
  22.     RelativeLayout>  
  23.   
  24.     <RelativeLayout  
  25.         android:id="@+id/ly_chat_bottom"  
  26.         android:layout_width="fill_parent"  
  27.         android:layout_height="55dp"  
  28.         android:layout_alignParentBottom="true"  
  29.         android:background="@drawable/bottom_bar" >  
  30.   
  31.         <Button  
  32.             android:id="@+id/id_chat_send"  
  33.             android:layout_width="60dp"  
  34.             android:layout_height="40dp"  
  35.             android:layout_alignParentRight="true"  
  36.             android:layout_centerVertical="true"  
  37.             android:layout_marginRight="10dp"  
  38.             android:background="@drawable/chat_send_btn"  
  39.             android:onClick="sendMessage"  
  40.             android:text="发送" />  
  41.   
  42.         <EditText  
  43.             android:id="@+id/id_chat_msg"  
  44.             android:layout_width="fill_parent"  
  45.             android:layout_height="40dp"  
  46.             android:layout_centerVertical="true"  
  47.             android:layout_marginLeft="10dp"  
  48.             android:layout_marginRight="10dp"  
  49.             android:layout_toLeftOf="@id/id_chat_send"  
  50.             android:background="@drawable/login_edit_normal"  
  51.             android:singleLine="true"  
  52.             android:textSize="18sp" />  
  53.     RelativeLayout>  
  54.   
  55.     <ListView  
  56.         android:id="@+id/id_chat_listView"  
  57.         android:layout_width="fill_parent"  
  58.         android:layout_height="fill_parent"  
  59.         android:layout_above="@id/ly_chat_bottom"  
  60.         android:layout_below="@id/ly_chat_title"  
  61.         android:cacheColorHint="#0000"  
  62.         android:divider="@null"  
  63.         android:dividerHeight="5dp"  
  64.         android:scrollbarStyle="outsideOverlay" >  
  65.     ListView>  
  66.   
  67. RelativeLayout>  

就是ListView和下面的消息框和消息按钮了~没撒好说的

3、HttpUtils

封装了一个用于访问API的工具类,其实就一个Get请求:

[java]  view plain copy
  1. package com.zhy.utils;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9. import java.net.URLEncoder;  
  10. import java.util.Date;  
  11.   
  12. import com.example.android_robot_01.bean.ChatMessage;  
  13. import com.example.android_robot_01.bean.ChatMessage.Type;  
  14. import com.example.android_robot_01.bean.CommonException;  
  15. import com.example.android_robot_01.bean.Result;  
  16. import com.google.gson.Gson;  
  17.   
  18. public class HttpUtils  
  19. {  
  20.     private static String API_KEY = "534dc342ad15885dffc10d7b5f813451";  
  21.     private static String URL = "http://www.tuling123.com/openapi/api";  
  22.   
  23.     /** 
  24.      * 发送一个消息,并得到返回的消息 
  25.      * @param msg 
  26.      * @return 
  27.      */  
  28.     public static ChatMessage sendMsg(String msg)  
  29.     {  
  30.         ChatMessage message = new ChatMessage();  
  31.         String url = setParams(msg);  
  32.         String res = doGet(url);  
  33.         Gson gson = new Gson();  
  34.         Result result = gson.fromJson(res, Result.class);  
  35.           
  36.         if (result.getCode() > 400000 || result.getText() == null  
  37.                 || result.getText().trim().equals(""))  
  38.         {  
  39.             message.setMsg("该功能等待开发...");  
  40.         }else  
  41.         {  
  42.             message.setMsg(result.getText());  
  43.         }  
  44.         message.setType(Type.INPUT);  
  45.         message.setDate(new Date());  
  46.           
  47.         return message;  
  48.     }  
  49.   
  50.     /** 
  51.      * 拼接Url 
  52.      * @param msg 
  53.      * @return 
  54.      */  
  55.     private static String setParams(String msg)  
  56.     {  
  57.         try  
  58.         {  
  59.             msg = URLEncoder.encode(msg, "UTF-8");  
  60.         } catch (UnsupportedEncodingException e)  
  61.         {  
  62.             e.printStackTrace();  
  63.         }  
  64.         return URL + "?key=" + API_KEY + "&info=" + msg;  
  65.     }  
  66.   
  67.     /** 
  68.      * Get请求,获得返回数据 
  69.      * @param urlStr 
  70.      * @return 
  71.      */  
  72.     private static String doGet(String urlStr)  
  73.     {  
  74.         URL url = null;  
  75.         HttpURLConnection conn = null;  
  76.         InputStream is = null;  
  77.         ByteArrayOutputStream baos = null;  
  78.         try  
  79.         {  
  80.             url = new URL(urlStr);  
  81.             conn = (HttpURLConnection) url.openConnection();  
  82.             conn.setReadTimeout(5 * 1000);  
  83.             conn.setConnectTimeout(5 * 1000);  
  84.             conn.setRequestMethod("GET");  
  85.             if (conn.getResponseCode() == 200)  
  86.             {  
  87.                 is = conn.getInputStream();  
  88.                 baos = new ByteArrayOutputStream();  
  89.                 int len = -1;  
  90.                 byte[] buf = new byte[128];  
  91.   
  92.                 while ((len = is.read(buf)) != -1)  
  93.                 {  
  94.                     baos.write(buf, 0, len);  
  95.                 }  
  96.                 baos.flush();  
  97.                 return baos.toString();  
  98.             } else  
  99.             {  
  100.                 throw new CommonException("服务器连接错误!");  
  101.             }  
  102.   
  103.         } catch (Exception e)  
  104.         {  
  105.             e.printStackTrace();  
  106.             throw new CommonException("服务器连接错误!");  
  107.         } finally  
  108.         {  
  109.             try  
  110.             {  
  111.                 if (is != null)  
  112.                     is.close();  
  113.             } catch (IOException e)  
  114.             {  
  115.                 e.printStackTrace();  
  116.             }  
  117.   
  118.             try  
  119.             {  
  120.                 if (baos != null)  
  121.                     baos.close();  
  122.             } catch (IOException e)  
  123.             {  
  124.                 e.printStackTrace();  
  125.             }  
  126.             conn.disconnect();  
  127.         }  
  128.   
  129.     }  
  130.   
  131. }  

暴露出去的,就是sendMsg这个静态方法,当然将返回的数据也直接封装成了ChatMessage

4、ChatMessage

[java]  view plain copy
  1. package com.example.android_robot_01.bean;  
  2.   
  3. import java.text.DateFormat;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Date;  
  6.   
  7. public class ChatMessage  
  8. {  
  9.   
  10.     /** 
  11.      * 消息类型 
  12.      */  
  13.     private Type type ;  
  14.     /** 
  15.      * 消息内容 
  16.      */  
  17.     private String msg;  
  18.     /** 
  19.      * 日期 
  20.      */  
  21.     private Date date;  
  22.     /** 
  23.      * 日期的字符串格式 
  24.      */  
  25.     private String dateStr;  
  26.     /** 
  27.      * 发送人 
  28.      */  
  29.     private String name;  
  30.   
  31.     public enum Type  
  32.     {  
  33.         INPUT, OUTPUT  
  34.     }  
  35.   
  36.     public ChatMessage()  
  37.     {  
  38.     }  
  39.   
  40.     public ChatMessage(Type type, String msg)  
  41.     {  
  42.         super();  
  43.         this.type = type;  
  44.         this.msg = msg;  
  45.         setDate(new Date());  
  46.     }  
  47.   
  48.     public String getDateStr()  
  49.     {  
  50.         return dateStr;  
  51.     }  
  52.   
  53.     public Date getDate()  
  54.     {  
  55.         return date;  
  56.     }  
  57.   
  58.     public void setDate(Date date)  
  59.     {  
  60.         this.date = date;  
  61.         DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  62.         this.dateStr = df.format(date);  
  63.   
  64.     }  
  65.   
  66.     public String getName()  
  67.     {  
  68.         return name;  
  69.     }  
  70.   
  71.     public void setName(String name)  
  72.     {  
  73.         this.name = name;  
  74.     }  
  75.   
  76.     public Type getType()  
  77.     {  
  78.         return type;  
  79.     }  
  80.   
  81.     public void setType(Type type)  
  82.     {  
  83.         this.type = type;  
  84.     }  
  85.   
  86.     public String getMsg()  
  87.     {  
  88.         return msg;  
  89.     }  
  90.   
  91.     public void setMsg(String msg)  
  92.     {  
  93.         this.msg = msg;  
  94.     }  
  95.   
  96. }  
都没撒好说的,很简单~

5、主Activity

[java]  view plain copy
  1. package com.example.android_robot_01;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Date;  
  5. import java.util.List;  
  6.   
  7. import android.app.Activity;  
  8. import android.content.Context;  
  9. import android.os.Bundle;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.text.TextUtils;  
  13. import android.view.View;  
  14. import android.view.Window;  
  15. import android.view.inputmethod.InputMethodManager;  
  16. import android.widget.EditText;  
  17. import android.widget.ListView;  
  18. import android.widget.Toast;  
  19.   
  20. import com.example.android_robot_01.bean.ChatMessage;  
  21. import com.example.android_robot_01.bean.ChatMessage.Type;  
  22. import com.zhy.utils.HttpUtils;  
  23.   
  24. public class MainActivity extends Activity  
  25. {  
  26.     /** 
  27.      * 展示消息的listview 
  28.      */  
  29.     private ListView mChatView;  
  30.     /** 
  31.      * 文本域 
  32.      */  
  33.     private EditText mMsg;  
  34.     /** 
  35.      * 存储聊天消息 
  36.      */  
  37.     private List mDatas = new ArrayList();  
  38.     /** 
  39.      * 适配器 
  40.      */  
  41.     private ChatMessageAdapter mAdapter;  
  42.   
  43.     private Handler mHandler = new Handler()  
  44.     {  
  45.         public void handleMessage(android.os.Message msg)  
  46.         {  
  47.             ChatMessage from = (ChatMessage) msg.obj;  
  48.             mDatas.add(from);  
  49.             mAdapter.notifyDataSetChanged();  
  50.             mChatView.setSelection(mDatas.size() - 1);  
  51.         };  
  52.     };  
  53.   
  54.     @Override  
  55.     protected void onCreate(Bundle savedInstanceState)  
  56.     {  
  57.         super.onCreate(savedInstanceState);  
  58.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  59.         setContentView(R.layout.main_chatting);  
  60.           
  61.         initView();  
  62.           
  63.         mAdapter = new ChatMessageAdapter(this, mDatas);  
  64.         mChatView.setAdapter(mAdapter);  
  65.   
  66.     }  
  67.   
  68.     private void initView()  
  69.     {  
  70.         mChatView = (ListView) findViewById(R.id.id_chat_listView);  
  71.         mMsg = (EditText) findViewById(R.id.id_chat_msg);  
  72.         mDatas.add(new ChatMessage(Type.INPUT, "我是小貅貅,很高兴为您服务"));  
  73.     }  
  74.   
  75.     public void sendMessage(View view)  
  76.     {  
  77.         final String msg = mMsg.getText().toString();  
  78.         if (TextUtils.isEmpty(msg))  
  79.         {  
  80.             Toast.makeText(this"您还没有填写信息呢...", Toast.LENGTH_SHORT).show();  
  81.             return;  
  82.         }  
  83.   
  84.         ChatMessage to = new ChatMessage(Type.OUTPUT, msg);  
  85.         to.setDate(new Date());  
  86.         mDatas.add(to);  
  87.   
  88.         mAdapter.notifyDataSetChanged();  
  89.         mChatView.setSelection(mDatas.size() - 1);  
  90.   
  91.         mMsg.setText("");  
  92.   
  93.         // 关闭软键盘  
  94.         InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
  95.         // 得到InputMethodManager的实例  
  96.         if (imm.isActive())  
  97.         {  
  98.             // 如果开启  
  99.             imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,  
  100.                     InputMethodManager.HIDE_NOT_ALWAYS);  
  101.             // 关闭软键盘,开启方法相同,这个方法是切换开启与关闭状态的  
  102.         }  
  103.   
  104.         new Thread()  
  105.         {  
  106.             public void run()  
  107.             {  
  108.                 ChatMessage from = null;  
  109.                 try  
  110.                 {  
  111.                     from = HttpUtils.sendMsg(msg);  
  112.                 } catch (Exception e)  
  113.                 {  
  114.                     from = new ChatMessage(Type.INPUT, "服务器挂了呢...");  
  115.                 }  
  116.                 Message message = Message.obtain();  
  117.                 message.obj = from;  
  118.                 mHandler.sendMessage(message);  
  119.             };  
  120.         }.start();  
  121.   
  122.     }  
  123.   
  124. }  

为ListView设置数据,一开始就设置了第一句话“我是小貅貅,很高兴为您服务”;还有就是sendButton的事件处理。

6、适配器

[java]  view plain copy
  1. package com.example.android_robot_01;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.content.Context;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.widget.BaseAdapter;  
  10. import android.widget.TextView;  
  11.   
  12. import com.example.android_robot_01.bean.ChatMessage;  
  13. import com.example.android_robot_01.bean.ChatMessage.Type;  
  14.   
  15. public class ChatMessageAdapter extends BaseAdapter  
  16. {  
  17.     private LayoutInflater mInflater;  
  18.     private List mDatas;  
  19.   
  20.     public ChatMessageAdapter(Context context, List datas)  
  21.     {  
  22.         mInflater = LayoutInflater.from(context);  
  23.         mDatas = datas;  
  24.     }  
  25.   
  26.     @Override  
  27.     public int getCount()  
  28.     {  
  29.         return mDatas.size();  
  30.     }  
  31.   
  32.     @Override  
  33.     public Object getItem(int position)  
  34.     {  
  35.         return mDatas.get(position);  
  36.     }  
  37.   
  38.     @Override  
  39.     public long getItemId(int position)  
  40.     {  
  41.         return position;  
  42.     }  
  43.   
  44.     /** 
  45.      * 接受到消息为1,发送消息为0 
  46.      */  
  47.     @Override  
  48.     public int getItemViewType(int position)  
  49.     {  
  50.         ChatMessage msg = mDatas.get(position);  
  51.         return msg.getType() == Type.INPUT ? 1 : 0;  
  52.     }  
  53.   
  54.     @Override  
  55.     public int getViewTypeCount()  
  56.     {  
  57.         return 2;  
  58.     }  
  59.   
  60.     @Override  
  61.     public View getView(int position, View convertView, ViewGroup parent)  
  62.     {  
  63.         ChatMessage chatMessage = mDatas.get(position);  
  64.   
  65.         ViewHolder viewHolder = null;  
  66.   
  67.         if (convertView == null)  
  68.         {  
  69.             viewHolder = new ViewHolder();  
  70.             if (chatMessage.getType() == Type.INPUT)  
  71.             {  
  72.                 convertView = mInflater.inflate(R.layout.main_chat_from_msg,  
  73.                         parent, false);  
  74.                 viewHolder.createDate = (TextView) convertView  
  75.                         .findViewById(R.id.chat_from_createDate);  
  76.                 viewHolder.content = (TextView) convertView  
  77.                         .findViewById(R.id.chat_from_content);  
  78.                 convertView.setTag(viewHolder);  
  79.             } else  
  80.             {  
  81.                 convertView = mInflater.inflate(R.layout.main_chat_send_msg,  
  82.                         null);  
  83.   
  84.                 viewHolder.createDate = (TextView) convertView  
  85.                         .findViewById(R.id.chat_send_createDate);  
  86.                 viewHolder.content = (TextView) convertView  
  87.                         .findViewById(R.id.chat_send_content);  
  88.                 convertView.setTag(viewHolder);  
  89.             }  
  90.   
  91.         } else  
  92.         {  
  93.             viewHolder = (ViewHolder) convertView.getTag();  
  94.         }  
  95.   
  96.         viewHolder.content.setText(chatMessage.getMsg());  
  97.         viewHolder.createDate.setText(chatMessage.getDateStr());  
  98.   
  99.         return convertView;  
  100.     }  
  101.   
  102.     private class ViewHolder  
  103.     {  
  104.         public TextView createDate;  
  105.         public TextView name;  
  106.         public TextView content;  
  107.     }  
  108.   
  109. }  

唯一需要注意的是,因为我们的ListView的Item有两种显示风格,所以比平时我们需要多重写两个方法:

[java]  view plain copy
  1. /** 
  2.      * 接受到消息为1,发送消息为0 
  3.      */  
  4.     @Override  
  5.     public int getItemViewType(int position)  
  6.     {  
  7.         ChatMessage msg = mDatas.get(position);  
  8.         return msg.getType() == Type.INPUT ? 1 : 0;  
  9.     }  
  10.   
  11.     @Override  
  12.     public int getViewTypeCount()  
  13.     {  
  14.         return 2;  
  15.     }  

getViewTypeCount返回的就是种类数目了;getItemViewType根据当然Item的position决定返回不同的整型变量。然后在getView中,根据消息的类型去加载不同的Item布局即可。


基本上也就完工了,没啥技术含量,纯属娱乐,各位程序猿兄,没事可以花点时间写下玩一玩~劳逸结合下~


源码点击下载


更多相关文章

  1. Android动态创建布局常用方法
  2. Android(安卓)自定义进度条ColorfulProgressBar,原理简单、效果很
  3. Android(安卓)ViewPager
  4. (转摘)Android腾讯微博客户端开发二:相关工具篇
  5. Android源码(9) --- Binder(3) AIDL使用
  6. 20162319 实验四 Android程序设计
  7. android内部培训视频_第二节 布局基础
  8. [React Native Android(安卓)安利系列]样式与布局的书写
  9. Android启动Activity之后阻止EditText自动获得焦点

随机推荐

  1. Android(安卓)桌面请求录屏权限不唤起App
  2. Android即时通讯
  3. Android(安卓)studio中TextView改变字体
  4. Android(Java)加载SO文件
  5. android 图片压缩,bitmap压缩总结
  6. Android(安卓)淘宝APP 开发入门篇(一)
  7. [置顶] android人脸识别——HowOld测测你
  8. Android应用开发提高系列(1)――《Practica
  9. Android横屏开发的老梗---Fragment切换混
  10. 苹果发大招 Android用户轻松迁移ios