Android Studio实现智能聊天
作者:醉流年 发布时间:2021-10-03 09:56:18
标签:Android,Studio,聊天
本文实例为大家分享了Android Studio实现智能聊天的具体代码,供大家参考,具体内容如下
1、布局activit_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/recycle">
</androidx.recyclerview.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/input"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/send"
android:text="发送"/>
</LinearLayout>
</LinearLayout>
2、创建子布局msg_item,显示聊天对话框
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/left_layout"
android:layout_gravity="left"
android:background="@drawable/message_left">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="10dp"
android:id="@+id/left_msg"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/right_layout"
android:layout_gravity="right"
android:layout_marginLeft="10dp"
android:background="@drawable/message_right">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="10dp"
android:id="@+id/right_msg"/>
</LinearLayout>
3、创建类Msg获取数据
public class Msg {
public static final int MSG_RECEIVED = 0;
public static final int MSG_SEND =1 ;
private String content;
private int type;
public Msg(String content,int type){
this.content=content;
this.type=type;
}
public String getContent() {
return content;
}
public int getType() {
return type;
}
}
4、创建RecyclerView的适配器,MsgAdapter继RecyclerView.Adapter<MsgAdapter.ViewHolder>
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
private List<Msg> mMsgList;
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
TextView leftMsg;
LinearLayout rightLayout;
TextView rightMsg;
public ViewHolder(@NonNull View itemView) {
super(itemView);
leftLayout=itemView.findViewById(R.id.left_layout);
rightLayout=itemView.findViewById(R.id.right_layout);
leftMsg=itemView.findViewById(R.id.left_msg);
rightMsg=itemView.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List<Msg> msgList){
mMsgList=msgList;
}
@NonNull
@Override
public MsgAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
ViewHolder holder=new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MsgAdapter.ViewHolder holder, int position) {
Msg msg=mMsgList.get(position);
if (msg.getType()==Msg.MSG_RECEIVED){
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
}else if (msg.getType()==Msg.MSG_SEND){
holder.leftLayout.setVisibility(View.GONE);
holder.rightLayout.setVisibility(View.VISIBLE);
holder.rightMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
5、创建 RobotManager类封装网络,网络地址:青云客,智能聊天机器人
public class RobotManager {
private static String Url="http://api.qingyunke.com/api.php?key=free&appid=0&msg=!!";
public static String getUrl(String question){
String real_Url=Url.replace("!!",question);
return real_Url;
}
}
6、逻辑
public class MainActivity extends AppCompatActivity {
private static String TAG="MainActivity";
private List<Msg> msgList = new ArrayList<>();
private EditText input;
private RecyclerView recyclerView;
private LinearLayoutManager manager;
private Button button;
private MsgAdapter adapter;
private String input_text;
private StringBuilder response;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//获取解析数据,显示在Recycle中
Bundle data = msg.getData();
String result = data.getString("result");
Msg msg_get = new Msg(result, Msg.MSG_RECEIVED);
msgList.add(msg_get);
//数据刷新
adapter.notifyItemInserted(msgList.size() - 1);
recyclerView.scrollToPosition(msgList.size() - 1);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initMsg();//初始化数据
recyclerView = findViewById(R.id.recycle);
button = findViewById(R.id.send);
input = findViewById(R.id.input);
manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
adapter = new MsgAdapter(msgList);
recyclerView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
input_text = input.getText().toString();
Msg msg = new Msg(input_text, Msg.MSG_SEND);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
recyclerView.scrollToPosition(msgList.size() - 1);
input.setText("");
getInter(); //发起网络请求
}
});
}
private void getInter() {
//开起线程
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(RobotManager.getUrl(input_text));
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(8000);
connection.setConnectTimeout(8000);
InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 2,解析获得的数据
Gson gson=new Gson();
Msg msg=gson.fromJson(response.toString(),Msg.class);
Log.d(TAG, "result:" + msg.getType());
Log.d(TAG, "content:" + msg.getContent());
// 3,将解析的数据保存到 Message中,传递到主线程中显示
Bundle data=new Bundle();
Message msg1=new Message();
if (msg.getType()==0){
data.putString("result",msg.getContent());
}else {
data.putString("result","我不知道你在说什么!");
}
msg1.setData(data);
msg1.what=1;
handler.sendMessage(msg1);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
private void initMsg() {
Msg msg = new Msg("我是菲菲,快来和我聊天吧!", Msg.MSG_RECEIVED);
msgList.add(msg);
}
}
来源:https://blog.csdn.net/weixin_63307826/article/details/123942426
0
投稿
猜你喜欢
- 前言在上一篇,我们谈到了jvm垃圾回收算法详细解析,并了解了JVM中针对堆区中不同的分代采用不同的垃圾回收算法在了解了垃圾回收算法之后,很多
- static和@Component遇到的bug今天在编写util的时候,发现不能调用到工具类里面的方法,转眼一看,原来不是工具类里面的方法是
- 0 写在前面在实际工作中有一些地方需要用到截取字符串的方法,所以在此记录下截取字符串的几种方法。.substring()StringUtil
- 声明式事务很方便,尤其纯注解模式,仅仅几个注解就能控制事务了思考:这些注解都做了什么?好神奇!@EnableTransactionManag
- Java与Oracle实现事务(JDBC事务)实例详解J2EE支持JDBC事务、JTA事务和容器事务事务,这里说一下怎样实现JDBC事务。&
- 具体实现过程不多说了,直接贴代码了。using System;using System.Collections.Generic;using
- 一、使用SchedulingConfigurer实现多个定时任务示例参考lz此博文链接二、定时任务多机器部署解决方案方式一:拆分,单独拆分出
- mybatis count()按条件查询1、sql count()函数count()函数返回匹配指定条件的行数。sql count(colu
- 以下我们系统通过原理,过程等方便给大家深入的简介了Java NIO的函数机制以及用法等,学习下吧。前言本篇主要讲解Java中的IO机制分为两
- Android webveiw 出现栈错误解决办法前言:最近做一个项目,项目调试基础库的一个调试工具展示设备信息页面使用WebView。有一
- 详解 Corba开发之Java实现Service与Client1 概述
- 在很多场景中我们需要验证时间日期的是否属于正确的格式,验证时间是否符合常规的。1、验证 yyyy-MM-dd HH:mm:dd 格式的日期S
- 泛型与类型擦除泛型,JDK 1.5新特性,本质是参数化类型(Parametersized Type) 的应用,即所操作的数据类型被指定为一个
- java使用贪心算法解决电台覆盖问题代码实现/** * 贪心算法实现集合覆盖 */public class Demo { &n
- 实现思路制作一个用户头像选择器仿 WeGame制作一个用户头像选择Canvas为父控件所实现,展示图片使用Image,Path当作
- 一、静态代理模式1.1、 代理模式的定义:由于某些原因需要给某对象提供一个代理以控制对该对象的访问。这时,访问对象不适合或者不能直接引用目标
- 类型转换Convert.To类型()1、表达式将变量和字面值(在使用运算符时,他们都称作操作数)与运算符组合起来就得到了表达式,它是计算的基
- 这篇文章主要介绍了springboot配置aop切面日志打印过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习
- Spring Cloud 为开发人员提供了一系列的工具来快速构建分布式系统的通用模型 。例如:配置管理、服务发现、断路由、智能路由、微代理、
- BeanDefinitionRegistryPostProcessor概述可以看到BeanDefinitionRegistryPostPro