图灵机器人+RecyclerView 多种Item布局时的处理,实现聊天对话的界面

    xiaoxiao2022-07-04  193

    准备工作(也很重要)

    首先导入依赖:

    implementation 'com.android.support:recyclerview-v7:28.0.0'

    添加网络权限还有一些其他的权限:(切记真机测试时打开网络)

    <uses-permission android:name="android.permission.RECORD_AUDIO" />            <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />            <uses-permission android:name="android.permission.INTERNET" />            <uses-permission android:name="android.permission.READ_PHONE_STATE" />            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />            <uses-permission android:name="android.permission.READ_CONTACTS" />            <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    在文件res—>values—>strings.xml中添加:(在主活动的布局文件中使用)

    <color name="colorText">#DEE1E6</color>

    在文件res—>drawable中添加一张图并且命名为 left.jpg或者(left.png)都可以:如图

     

    创建适配器:

    创建Left适配器继承自 RecyclerView.Adapter<Left.ViewHolder>

    import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; public class Left extends RecyclerView.Adapter<Left.ViewHolder> { private List<Msg> mlist; private Context mContext; public Left(List<Msg> list, Context context){ this.mlist=list; this.mContext=context; } public class ViewHolder extends RecyclerView.ViewHolder { LinearLayout leftLayout; LinearLayout rightLayout; TextView leftText; TextView rightText; public ViewHolder(View itemView) { super(itemView); leftLayout=itemView.findViewById(R.id.left); rightLayout=itemView.findViewById(R.id.right); leftText=itemView.findViewById(R.id.left_text); rightText=itemView.findViewById(R.id.right_text); } } @Override public ViewHolder onCreateViewHolder( ViewGroup viewGroup, int i) { View view=LayoutInflater.from(mContext).inflate(R.layout.item,viewGroup,false); return new ViewHolder(view); } @Override public void onBindViewHolder( ViewHolder viewHolder, int i) { final Msg msg=mlist.get(i); switch (msg.getType()){ case RECEIVED: viewHolder.leftLayout.setVisibility(View.VISIBLE); viewHolder.rightLayout.setVisibility(View.GONE); viewHolder.leftText.setText(msg.getContent()); break; case SENT: viewHolder.leftLayout.setVisibility(View.GONE); viewHolder.rightLayout.setVisibility(View.VISIBLE); viewHolder.rightText.setText(msg.getContent()); break; } } /* * 告诉RecyclerView一共有多少个子项,直接返回数据源长度 * */ @Override public int getItemCount() { return mlist.size(); } }

     

    RecyclerView的子项布局:在res—>layout文件下创建item.xml文件;

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:android="http://schemas.android.com/apk/res/android"> <LinearLayout android:id="@+id/left" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/left" android:scaleType="fitXY" android:layout_margin="5dp" /> <TextView android:id="@+id/left_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:gravity="left" /> </LinearLayout> <LinearLayout android:id="@+id/right" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/right_text" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginLeft="5dp" android:layout_marginRight="5dp" android:gravity="right" /> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:src="@drawable/left" android:scaleType="fitXY" android:layout_margin="5dp" /> </LinearLayout> </LinearLayout>

    创建主活动:

    网络请求执行有两种:(okhttp3网络框架)——(详细区别自行百度)

          1.同步执行:execute()方法,网络请求不能放在主线程中,所以要创建子线程执行

    new Thread(new Runnable() { @Override public void run() { /* *此处写你需要运行的事件 * */ } }).start();

           2.异步执行:enqueue(),异步执行的方法已注掉

     

    主活动:(复制粘贴时一定要注意所有布局 id 和 控件 id 是否和你自己设置的一致)

    package com.example.ft.valuesstyle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.ft.valuesstyle.net.Api; import com.google.gson.Gson; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /* * 1.第三方api的学习 图灵机器人 * 2.RecyclerView 多种Item布局时的处理,实现聊天对话的界面 * */ public class MainActivity extends AppCompatActivity implements View.OnClickListener { private List<Msg> list=new ArrayList(); private RecyclerView recyclerView; private Button button; private EditText editText; private String data_r; private String data_l=""; private Left left; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText=findViewById(R.id.data_view); button=findViewById(R.id.send); recyclerView=findViewById(R.id.re_view); LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.send: sentData(); /*try { aa(data_r); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }*/ /* * 此循环判断data_l是否被赋值了 * */ request(data_r); while (true){ if(!data_l.equals("")){ break; } } addData(data_l,Msg.TYPE.RECEIVED); // left=new Left(list,this); recyclerView.setAdapter(left); //当有新消息时,刷新显示 left.notifyItemInserted(list.size() - 1); //定位的最后一行 recyclerView.scrollToPosition(list.size()-1); editText.setText(""); //完成后清空全局变量 data_l=""; break; } } private void sentData(){ data_r=editText.getText().toString(); Msg msg=new Msg(this.data_r,Msg.TYPE.SENT); list.add(msg); } private void addData(String data, Msg.TYPE type){ Msg msg=new Msg(data,type); list.add(msg); } public void aa(String data) throws JSONException, IOException { Map map = new HashMap<>(); map.put("text", data); Map map1 = new HashMap<>(); map1.put("inputText", map); Map map2 = new HashMap(); map2.put("apiKey", "c00282de107144fb940adab994d9ff98"); map2.put("userId", "225167"); Map map3 = new HashMap(); map3.put("reqType", 0); map3.put("perception", map1); map3.put("userInfo", map2); Gson gson = new Gson(); String param = gson.toJson(map3); MediaType mediaType1 = MediaType.parse("application/json; charset=utf-8"); final Request request = new Request.Builder() .url("http://openapi.tuling123.com/openapi/api/v2") .post(RequestBody.create(mediaType1, param)) .build(); final OkHttpClient okHttpClient = new OkHttpClient(); /* * 同步执行 核心为这个execute()方法 * */ //ResponseBody response=okHttpClient.newCall(request).execute().body(); new Thread(new Runnable() { @Override public void run() { okhttp3.Call call=okHttpClient.newCall(request); try { okhttp3.Response response = call.execute(); String data1 =response.body().string(); JSONObject jsonObject = JSONUtil.parseObj(data1); System.out.println(jsonObject.get("results")); String results = jsonObject.get("results").toString().replace("[", "").replace("]", ""); JSONObject jsonObject1 = JSONUtil.parseObj(results); System.out.println(jsonObject1.get("values")); String values = jsonObject1.get("values").toString(); JSONObject jsonObject2 = JSONUtil.parseObj(values); System.out.println(jsonObject2.get("text")); data_l = jsonObject2.get("text").toString(); } catch (IOException e) { e.printStackTrace(); } } }).start(); /* * 异步执行 核心为这个enqueue()方法 * */ /* OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(okhttp3.Call call, IOException e) { } @Override public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException { ResponseBody responseBody = response.body(); JSONObject jsonObject = JSONUtil.parseObj(responseBody.string()); System.out.println(jsonObject.get("results")); String results = jsonObject.get("results").toString().replace("[", "").replace("]", ""); JSONObject jsonObject1 = JSONUtil.parseObj(results); System.out.println(jsonObject1.get("values")); String values = jsonObject1.get("values").toString(); JSONObject jsonObject2 = JSONUtil.parseObj(values); System.out.println(jsonObject2.get("text")); data_l = jsonObject2.get("text").toString(); } });*/ } }

     

    创建主活动的布局文件

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/re_view" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent"> </android.support.v7.widget.RecyclerView> <LinearLayout android:layout_gravity="end" android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <EditText android:id="@+id/data_view" android:layout_width="0dp" android:layout_weight="1" android:layout_height="50dp" android:layout_marginLeft="5dp" android:layout_marginRight="5dp"/> <Button android:text="发送" android:layout_marginRight="5dp" android:layout_gravity="center|right" android:layout_width="60sp" android:layout_height="40dp" android:textColor="@color/colorText" android:background="@color/colorPrimary" android:id="@+id/send"/> </LinearLayout> </LinearLayout>

     如果用到了就点个赞!!!

     

    最新回复(0)