先看在网络上访问机器人的聊天效果
image.png
第一步咱们先来一个主布局xml
<?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="match_parent"
android:background="#c2c2c2"
android:orientation="vertical"
android:padding="16dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/maowo"
android:orientation="vertical"
android:padding="8dp">
<ListView
android:id="@+id/lv_chat_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#0000"
android:dividerHeight="8dp"
android:scrollbars="none">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<EditText
android:id="@+id/et_chat_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14sp"
android:background="#fff"
android:gravity="center|left"
android:padding="8dp" />
<Button
android:id="@+id/btn_chat_message_send"
style="?android:attr/buttonStyleSmall"
android:layout_width="64dp"
android:text="发送"
android:textColor="#fff"
android:layout_marginLeft="8dp"
android:layout_height="match_parent"
android:layout_gravity="center|right"
android:layout_marginRight="4dp"
android:background="#1488F5" />
</LinearLayout>
</LinearLayout>
注意:@drawable/maowo 我是一张模糊的图片
然后咱们把加载ListView的Item布局写一下,一共有两个,一个是自己一个是他人
他人item
<?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="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="机器"
android:layout_marginBottom="20dp"
android:textSize="30sp"/>
<TextView
android:padding="5dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:id="@+id/jiqimcg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/xuan2"
android:text="我是一个机器人"
android:textColor="#fff"
android:textSize="20sp"/>
</LinearLayout>
自己item2
<?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="horizontal"
android:gravity="right">
<TextView
android:padding="5dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="@+id/tv_chat_me_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/xuan"
android:text="TextView"
android:textSize="20sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我"
android:layout_marginBottom="20dp"
android:textColor="#f0f"
android:textSize="30sp"/>
</LinearLayout>
对话框的背景可以自己设置,xuan,xhuan2
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#AEF2AC"/>
<corners
android:radius="100dp"
/>
</shape>
再来一个消息的数据类
package com.example.qqliao;
import android.util.Log;
/**
* Created by Administrator on 2018/7/11 0011.
*/
public class PersonChat {
/**
* id
*/
private int id;
/**
* 姓名
*/
private String name;
/**
* 聊天内容
*/
private String chatMessage;
private String jiqiMessage;
/**
*
* @return 是否为本人发送
*/
private boolean isMeSend;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getChatMessage() {
Log.e("tag","getChatMessage");
return chatMessage;
}
public void setChatMessage(String chatMessage) {
this.chatMessage = chatMessage;
}
public String getjiqiMessage() {
return jiqiMessage;
}
public void setjiqiMessage(String jiqiMessage) {
this.jiqiMessage = jiqiMessage;
}
/**
* 是否是自己发的消息
* @return
*/
public boolean isMeSend() {
return isMeSend;
}
public void setMeSend(boolean isMeSend) {
this.isMeSend = isMeSend;
}
public PersonChat(int id, String name, String chatMessage, boolean isMeSend) {
super();
this.id = id;
this.name = name;
this.chatMessage = chatMessage;
this.isMeSend = isMeSend;
}
public PersonChat() {
super();
}
}
主布局代码写
package com.example.qqliao;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.example.qqliao.com.example.qqliao.mychatt.ChatAdapter;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private ChatAdapter chatAdapter;
/**
* 声明ListView
*/
private ListView lv_chat_dialog;
/**
* 集合添加自己的PersonChat数据类可以调用此类的方法在适配器那边
*/
private ArrayList<PersonChat> personChats = new ArrayList<PersonChat>();
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
int what = msg.what;
switch (what) {
case 1:
/**
* ListView条目控制在最后一行
*/
lv_chat_dialog.setSelection(personChats.size());
break;
case 404:
Toast.makeText(MainActivity.this, "┗|`O′|┛ 嗷~~没有连到网罗罗哦", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
/**
* 虚拟1条发送方的消息
*/
PersonChat personChat = new PersonChat();
personChat.setMeSend(false);
personChat.setjiqiMessage("我是成龙2号");
personChats.add(personChat);
lv_chat_dialog = (ListView) findViewById(R.id.lv_chat_dialog);
Button btn_chat_message_send = (Button) findViewById(R.id.btn_chat_message_send);
final EditText et_chat_message = (EditText) findViewById(R.id.et_chat_message);
/**
*setAdapter
*/
chatAdapter = new ChatAdapter(this, personChats);
lv_chat_dialog.setAdapter(chatAdapter);
/**
* 发送按钮的点击事件
*/
btn_chat_message_send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (TextUtils.isEmpty(et_chat_message.getText().toString())) {
Toast.makeText(MainActivity.this, "发送内容不能为空", Toast.LENGTH_LONG).show();
return;
}
//数据类new出来添加数据添加到集合中
PersonChat personChat = new PersonChat();
//代表自己发送
personChat.setMeSend(true);
//得到发送内容
final String s = et_chat_message.getText().toString();
personChat.setChatMessage(s);
//加入集合
personChats.add(personChat);
//清空输入框
et_chat_message.setText("");
//刷新ListView
chatAdapter.notifyDataSetChanged();
//把List控制在最后一行
handler.sendEmptyMessage(1);
//代表别人发的(机器人)
new Thread(){//联网耗时在分线程中执行
@Override
public void run() {
PersonChat personChat2 = new PersonChat();
//设置是别人发的
personChat2.setMeSend(false);
//获得联网返回的数据
String phon2 = Phonl(s);
if(phon2!=null){
personChat2.setjiqiMessage(phon2);
}else {
personChat2.setjiqiMessage("┗|`O′|┛ 嗷~~没有连到网罗罗哦");
}
//添加集合
personChats.add(personChat2);
//然后刷新数据要在UI线程中执行runOnUiThread
runOnUiThread(new Runnable() {
@Override
public void run() {
chatAdapter.notifyDataSetChanged();
//在最后一行
handler.sendEmptyMessage(1);
}
});
}
}.start();//开启线程
}
});
}
public String Phonl(String info) {
try {
URL url = new URL("这里写自己的网址可以传入"+info+"和返回的JSON");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");//设置请求方式
urlConnection.setConnectTimeout(3000);//设置连接超时
urlConnection.setReadTimeout(2000);//设置请求超时
urlConnection.connect();//链接
if (urlConnection.getResponseCode() == 200) {//200 ok,404 找不到,503 服务器内部错误
// 网络输入流
InputStream inputStream = urlConnection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int lenth = -1;
while ((lenth = inputStream.read(data)) != -1) {
out.write(data, 0, lenth);
out.flush();
}
out.close();
inputStream.close();
String xinxi=out.toString();//获得Json格式字符串
JSONObject jsonObject = new JSONObject(xinxi);//解析Json格式字符串
int error_code = jsonObject.getInt("error_code");//具体写自己的JSON格式
if(error_code==0){
JSONObject result = jsonObject.getJSONObject("result");
String text = result.getString("text");
return text;
}
} else {
handler.sendEmptyMessage(404);
return null;
}
} catch (Exception e) {
handler.sendEmptyMessage(404);
return null;
}
handler.sendEmptyMessage(404);
return null;
}
}
适配器ChatAdapter写
package com.example.qqliao.com.example.qqliao.mychatt;
/**
* Created by Administrator on 2018/7/11 0011.
*/
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.qqliao.PersonChat;
import com.example.qqliao.R;
public class ChatAdapter extends BaseAdapter {
private Context context;
private List<PersonChat> lists;
public ChatAdapter(Context context, List<PersonChat> lists) {
super();
this.context = context;
this.lists = lists;
}
/**
* 是否是自己发送的消息
*
* @author cyf
*/
// public static interface IMsgViewType {
// int IMVT_COM_MSG = 0;// 收到对方的消息
// int IMVT_TO_MSG = 1;// 自己发送出去的消息
// }
@Override
public int getCount() {
// TODO Auto-generated method stub
return lists.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lists.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
/**
* 得到Item的类型,是对方发过来的消息,还是自己发送出去的
*/
// public int getItemViewType(int position) {
// PersonChat entity = lists.get(position);
// if (entity.isMeSend()) {// 收到的消息
// return IMsgViewType.IMVT_COM_MSG;
// } else {// 自己发送的消息
// return IMsgViewType.IMVT_TO_MSG;
// }
// }
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
PersonChat entity = lists.get(arg0);
boolean isMeSend = entity.isMeSend();
HolderView holderView = null;
if (holderView == null) {
holderView = new HolderView();
if (isMeSend) {
arg1 = View.inflate(context, R.layout.item2,
null);
holderView.tv_chat_me_message = (TextView) arg1
.findViewById(R.id.tv_chat_me_message);
} else {
arg1 = View.inflate(context, R.layout.item,
null);
holderView.jiqimcg = (TextView) arg1
.findViewById(R.id.jiqimcg);
}
arg1.setTag(holderView);
} else {
holderView = (HolderView) arg1.getTag();
}
if (isMeSend) {
holderView.tv_chat_me_message.setText(entity.getChatMessage());
} else {
holderView.jiqimcg.setText(entity.getjiqiMessage());
}
return arg1;
}
class HolderView {
TextView tv_chat_me_message;
TextView jiqimcg;
}
}
没错的情况下就可以运行了鷍😀
原网站可以访问:
https://www.cnblogs.com/yunfang/p/5553629.html
上面用了类转递还可以用ArrayList<HashMap<String,String>>集合传递数据
主代码
package com.example.wangye.robottest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
Button bt;
ListView listView;
EditText editText;
ArrayList<HashMap<String,String>> arrayList = new ArrayList<>();
MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init(){
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendDataToNet();
}
});
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.editText);
adapter = new MyAdapter(MainActivity.this,arrayList);
listView.setAdapter(adapter);
}
public void sendDataToNet(){
final String content = editText.getText().toString();
if(content == null || content.equals("")){
Toast.makeText(this, "发送内容不能为空", Toast.LENGTH_SHORT).show();
}else{
//不管用户是否联网 只要输入框不为空 就把内容刷新到ListView上
HashMap<String,String> map = new HashMap<>();
map.put("data",content);
map.put("label","person");
arrayList.add(map);
adapter.updateAdapter(arrayList);
listView.setSelection(arrayList.size()-1);
listView.setStackFromBottom(true);
editText.setText("");
new Thread(){
@Override
public void run() {
try {
URL url = new URL("http://op.juhe.cdex?info="
+ URLEncoder.encode(content,"UTF-8")
+"&dtype=&loc=&userid=&key=761522f85f516959958a310457c29735");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
con.connect();
if(con.getResponseCode() == 200){
InputStream is = con.getInputStream();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
byte buffer[] = new byte[512];
int length = -1;
while( ( length = is.read(buffer)) != -1){
bs.write(buffer,0,length);
bs.flush();
}
is.close();
bs.close();
JSONObject json = new JSONObject(bs.toString());
JSONObject jsonObject = json.getJSONObject("result");
String data = jsonObject.getString("text");
HashMap<String,String> map = new HashMap<>();
map.put("data",data);
map.put("label","robot");
arrayList.add(map);
runOnUiThread(new Thread(){
@Override
public void run() {
adapter.updateAdapter(arrayList);
listView.setSelection(arrayList.size()-1);
listView.setStackFromBottom(true);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
}
适配器
package com.example.wangye.robottest;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by wangye on 2018/7/12.
*/
public class MyAdapter extends BaseAdapter {
Context c;
ArrayList<HashMap<String, String>> arrayList;
public MyAdapter(Context c, ArrayList<HashMap<String, String>> arrayList) {
this.c = c;
this.arrayList = arrayList;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
//判断传过来的参数是谁的
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(arrayList.get(i).get("label").equals("person")){
view = View.inflate(c,R.layout.person,null);
TextView txPerson = view.findViewById(R.id.text_person);
txPerson.setText(arrayList.get(i).get("data"));
}else{
view = View.inflate(c,R.layout.robot,null);
TextView txRobot = view.findViewById(R.id.text_robot);
txRobot.setText(arrayList.get(i).get("data"));
}
return view;
}
//在这里更新效果会更好
public void updateAdapter(ArrayList<HashMap<String, String>> arrayList){
this.arrayList = arrayList;
notifyDataSetChanged();
}
}