kotlin实现语音聊天机器人案例详解

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

此篇文章完成后效果展示:

kotlin实现语音聊天机器人案例详解_第1张图片

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

1.准备两张左右两边动画背景图片,做left,和right两边布局,为Recyclerview的实现做准备。

left_item.xml



    
    

right_item.xml:



    
    

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

package com.zrc.smartbutler.entity
/**
 *项目名:  SmartButler
 *包名:    com.zrc.smartbutler.entity
 *文件名:  ChatListData
 *描述:    对话列表的实体类
 */
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
 *描述:    对话Adapter
 */
class ChatListAdapter (val mList:List): RecyclerView.Adapter() {
    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,编写界面交互代码:



    
    
        
        

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
 *描述:    服务管家
 */
class ButlerFragment:Fragment() {
    private val msgList = ArrayList()
    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()
        }
    }
}

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

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

到此这篇关于kotlin实现语音聊天机器人案例详解的文章就介绍到这了,更多相关kotlin聊天机器人内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(kotlin实现语音聊天机器人案例详解)