Android 简单的对话框

先看在网络上访问机器人的聊天效果

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();
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,542评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,822评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,912评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,449评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,500评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,370评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,193评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,074评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,505评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,722评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,841评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,569评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,168评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,783评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,918评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,962评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,781评论 2 354

推荐阅读更多精彩内容