智能管家App kotlin版(5)——语音机器人聊天开发

前言:Android智能问答机器人是时下非常流行的一种服务,微软“小冰”的出现更是让其实实在在的风靡了一把。那么,本文章就将带领大家完整的实现整个问答机器人的制作。

此篇文章紧做关于语音机器人聊天开发,后续功能实现请关注后续文章!!!

此篇文章完成后效果展示:
在这里插入图片描述

一.机器人聊天—对话adapter的实现

1.准备两张左右两边动画背景图片,做left,和right两边布局,为Recyclerview的实现做准备。
left_item.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="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:src="@drawable/assistant"/>


    <TextView
        android:id="@+id/tv_left_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:background="@drawable/chat_bg_cloud"
        android:gravity="center_vertical"
        android:padding="20dp"
        android:textColor="@android:color/white"/>

</LinearLayout>

right_item.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="wrap_content"
    android:gravity="right|center_vertical"
    android:orientation="horizontal">


    <TextView
        android:id="@+id/tv_right_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:background="@drawable/chat_bg_user"
        android:gravity="center_vertical"
        android:padding="20sp"
        android:textColor="@android:color/white"/>

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/user"/>

</LinearLayout>

2.在entity包下ChatListData对话列表的实体类,代码如下:

package com.zrc.smartbutler.entity

/**
 *项目名:  SmartButler
 *包名:    com.zrc.smartbutler.entity
 *文件名:  ChatListData
 *创建者:  张如成
 *创建时间: 2020/5/14 9:42
 *描述:    对话列表的实体类
 */
class ChatListData(var type:Int,var context:String){
    
    
    companion object{
    
    
        const val TyPE_RECEIVED = 0
        const val Type_SENT = 1
    }
}

3.在adapter包下创建ChatListAdapter对话Adapter,代码如下:

package com.zrc.smartbutler.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.zrc.smartbutler.R
import com.zrc.smartbutler.entity.ChatListData

/**
 *项目名:  SmartButler
 *包名:    com.zrc.smartbutler.adapter
 *文件名:  ChatListAdapter
 *创建者:  张如成
 *创建时间: 2020/5/14 9:40
 *描述:    对话Adapter
 */
class ChatListAdapter (val mList:List<ChatListData>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    
    

    inner class LeftViewHolder(view:View):RecyclerView.ViewHolder(view){
    
    
        val leftMsg:TextView = view.findViewById(R.id.tv_left_text)
    }

    inner class RightViewHolder(view:View):RecyclerView.ViewHolder(view){
    
    
        val rightMsg:TextView = view.findViewById(R.id.tv_right_text)
    }

    override fun getItemViewType(position: Int): Int {
    
    
        val msg = mList[position]
        return msg.type
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = if(viewType==ChatListData.TyPE_RECEIVED){
    
    
        val view = LayoutInflater.from(parent.context).inflate(R.layout.left_item,parent,false)
        LeftViewHolder(view)
    }else{
    
    
        val view = LayoutInflater.from(parent.context).inflate(R.layout.right_item,parent,false)
        RightViewHolder(view)
    }

    override fun getItemCount() = mList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    
    
        val msg = mList[position]
        when(holder){
    
    
            is LeftViewHolder -> holder.leftMsg.text = msg.context
            is RightViewHolder -> holder.rightMsg.text = msg.context
            else -> throw IllegalArgumentException()
        }
    }
}

这段代码,仿写自郭霖大神的第一行代码(第三版),详情解析,请查看第三行代码!

至此,对话adapter完成!!!

二.机器人聊天—机器人实时对话实现

1.导入RecyclerView依赖

implementation 'androidx.recyclerview:recyclerview:1.1.0

2.前往fragment_butler.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="@drawable/wechat_bg"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/inputText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入"
            android:maxLines="2"/>

        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:background="@drawable/button_bg"
            android:text="发送"/>
    </LinearLayout>
</LinearLayout>

3.编写Kotlin交互代码:

package com.zrc.smartbutler.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.kymjs.rxvolley.RxVolley
import com.kymjs.rxvolley.client.HttpCallback
import com.zrc.smartbutler.R
import com.zrc.smartbutler.adapter.ChatListAdapter
import com.zrc.smartbutler.entity.ChatListData
import com.zrc.smartbutler.utils.StaticClass
import kotlinx.android.synthetic.main.fragment_butler.view.*
import org.json.JSONException
import org.json.JSONObject

/**
 *项目名:  SmartButler
 *包名:    com.zrc.smartbutler.fragment
 *文件名:  ButlerFragment
 *创建者:  张如成
 *创建时间: 2020/5/6 9:07
 *描述:    服务管家
 */
class ButlerFragment:Fragment() {
    
    

    private val msgList = ArrayList<ChatListData>()
    private var adapter:ChatListAdapter?= null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    
    
        val view:View = inflater.inflate(R.layout.fragment_butler,null)

        findView()
        val layoutManager = LinearLayoutManager(this.context)
        view.recyclerView.layoutManager = layoutManager
        adapter = ChatListAdapter(msgList)
        view.recyclerView.adapter = adapter
        view.send.setOnClickListener {
    
    
            /**
             * 逻辑
             * 1.获取输入框的内容
             * 2.判断是否为空
             * 3.判断长度不能大于30
             * 4.添加你输入的内容到right item
             * 5.清空当前的输入框
             * 6.发送给机器人请求返回内容
             * 7.拿到机器人的返回值之后添加在left item
             */
            //1.获取输入框的内容
            val content = view.inputText.text.toString()
            //2.判断是否为空
            if(content.isNotEmpty()){
    
    
                //3.判断长度不能大于30
                if(content.length>30){
    
    
                    Toast.makeText(activity,"输入长度超出限制",Toast.LENGTH_SHORT).show()
                }else{
    
    
                    //4.添加你输入的内容到right item
                    val msg = ChatListData(ChatListData.Type_SENT,content)
                    msgList.add(msg)
                    adapter?.notifyItemInserted(msgList.size-1)//当有新消息时,刷新RecycleView中的显示
                    view.recyclerView.scrollToPosition(msgList.size-1)//讲RecycleView定位到最后一行
                    //5.清空当前的输入框
                    view.inputText.setText("")
                    //6.发送给机器人请求返回内容
                    //6.发送给机器人请求返回内容
                    val url = ("http://op.juhe.cn/robot/index?info=" + content + "&key=" + StaticClass().CHAT_LIST_KEY)
                    RxVolley.get(url,object :HttpCallback(){
    
    
                        override fun onSuccess(t: String?) {
    
    
                            //Toast.makeText(activity,t,Toast.LENGTH_SHORT).show()
                            parsingJson(t!!,view)
                        }
                    })

                }

            }else{
    
    
                Toast.makeText(activity,"输入框不能为空",Toast.LENGTH_SHORT).show()
            }
        }
        return view
    }

    private fun findView() {
    
    
        val msg1 = ChatListData(ChatListData.TyPE_RECEIVED,"你好,我是大雨子!!!")
        msgList.add(msg1)
    }

    //解析Json
    private fun parsingJson(t: String,view: View) {
    
    
        try {
    
    
            val jsonObhect = JSONObject(t)
            val jsonresult = jsonObhect.getJSONObject("result")
            //拿到返回值
            val text = jsonresult.getString("text")
            //7.拿到机器人的返回值之后添加在left item
            val msg = ChatListData(ChatListData.TyPE_RECEIVED,text)
            msgList.add(msg)
            adapter?.notifyItemInserted(msgList.size-1)//当有新消息时,刷新RecycleView中的显示
            view.recyclerView.scrollToPosition(msgList.size-1)//讲RecycleView定位到最后一行
        } catch (e: JSONException) {
    
    
            e.printStackTrace()
        }
    }
}

代码逻辑上面注释已经写清楚了,就不多赘述!!!

至此,机器人的对话实现!!!

语音机器人聊天开发完成,下篇文章将针对微信精选文章查看进行开发,欢迎关注后续更新!!!

おすすめ

転載: blog.csdn.net/weixin_43912367/article/details/106112219