Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發系列(十四):做出 QQ 風格的氣泡聊天介面

編輯:關於 Android 程式設計

這一課要實作一個類似 QQ 的聊天畫面:標題欄在上方、輸入區在下方、中間是可捲動的訊息列表,而訊息以左右分置的對話氣泡呈現。

整體構造思路

主體用 RelativeLayout,標題欄與輸入區各自是一個 LinearLayout 子配置,中間放一個自訂的 ListView。整個實作唯一特別的地方在於:ListView 的子項目有兩種版面配置——「我」發出的訊息靠右、用一份配置檔;對方發來的訊息靠左、用另一份。資料存在一個 ArrayList<HashMap> 中,在自訂 Adapter 的 getView() 裡依訊息來源挑選對應的項目配置即可。

主版面配置

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/chat_title"
        android:layout_width="match_parent"
        android:layout_height="44dip"
        android:layout_alignParentTop="true"
        android:background="@drawable/chat_title_layer" >

        <Button
            android:id="@+id/chat_msg_button"
            android:layout_width="match_parent"
            android:layout_height="36dip"
            android:layout_weight="1.9"
            android:layout_marginLeft="8dip"
            android:layout_marginTop="3dip"
            android:text="消息(0)"
            android:textColor="@android:color/white"
            android:textSize="7pt"
            android:background="@drawable/msg_button_back" />

        <TextView
            android:id="@+id/chat_contact_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="龍行天下"
            android:textSize="8pt"
            android:textColor="@android:color/white"
            android:gravity="center"
            android:layout_gravity="center_vertical" />

        <ImageButton
            android:id="@+id/chat_contact_button"
            android:layout_width="match_parent"
            android:layout_height="36dip"
            android:layout_weight="2"
            android:layout_marginRight="8dip"
            android:layout_marginTop="3dip"
            android:background="@drawable/chat_contact_back" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/chat_bottom_linear"
        android:layout_width="match_parent"
        android:layout_height="42dip"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:background="@drawable/chat_title_layer"
        android:paddingTop="7dip"
        android:paddingBottom="3dip" >

        <ImageButton
            android:id="@+id/chat_bottom_look"
            android:layout_width="match_parent"
            android:layout_height="26dip"
            android:layout_weight="3.5"
            android:layout_marginLeft="7dip"
            android:layout_marginTop="3dip"
            android:background="@drawable/chat_bottom_look" />

        <ImageButton
            android:id="@+id/chat_bottom_add"
            android:layout_width="match_parent"
            android:layout_height="26dip"
            android:layout_weight="3.5"
            android:layout_marginLeft="7dip"
            android:layout_marginTop="3dip"
            android:background="@drawable/chat_bottom_add" />

        <EditText
            android:id="@+id/chat_bottom_edittext"
            android:layout_width="match_parent"
            android:layout_height="32dip"
            android:layout_weight="1.5"
            android:layout_marginLeft="5dip"
            android:layout_marginRight="7dip"
            android:background="@drawable/edit_fillet_shape" />

        <Button
            android:id="@+id/chat_bottom_sendbutton"
            android:layout_width="match_parent"
            android:layout_height="26dip"
            android:layout_weight="3.2"
            android:layout_marginRight="4dip"
            android:layout_marginBottom="3dip"
            android:background="@drawable/chat_button_fillet_shape"
            android:text="發送"
            android:textColor="@android:color/white" />
    </LinearLayout>

    <ListView
        android:id="@+id/chat_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/chat_title"
        android:layout_above="@id/chat_bottom_linear"
        android:fadingEdge="none"
        android:background="#f0f0f0"
        android:divider="#aaaaaa"
        android:dividerHeight="0px" >
    </ListView>

</RelativeLayout>

「我」發出的訊息項目

靠右對齊,頭像放右側,氣泡在頭像左邊。左邊留 80dip 是為了避免文字长到超出畫面。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#f0f0f0"
    android:paddingLeft="80dip"
    android:paddingRight="8dip"
    android:paddingBottom="10dip"
    android:paddingTop="10dip" >

    <ImageView
        android:id="@+id/chatlist_image_me"
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_marginLeft="5dip"
        android:layout_alignParentRight="true"
        android:background="@drawable/contact_3" />

    <TextView
        android:id="@+id/chatlist_text_me"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/chatlist_image_me"
        android:layout_alignTop="@id/chatlist_image_me"
        android:text="會忽悠了gyughiulhlluihui過"
        android:background="@drawable/balloon_back_right"
        android:paddingTop="13dip"
        android:paddingBottom="18dip" />

</RelativeLayout>

「對方」發出的訊息項目

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#f0f0f0"
    android:paddingRight="80dip"
    android:paddingLeft="8dip"
    android:paddingBottom="10dip"
    android:paddingTop="10dip" >

    <ImageView
        android:id="@+id/chatlist_image_other"
        android:layout_width="40dip"
        android:layout_height="40dip"
        android:layout_marginRight="5dip"
        android:layout_alignParentLeft="true"
        android:background="@drawable/contact_3" />

    <TextView
        android:id="@+id/chatlist_text_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/chatlist_image_other"
        android:layout_alignTop="@id/chatlist_image_other"
        android:text="hewdfb"
        android:background="@drawable/balloon_back_left"
        android:paddingTop="13dip"
        android:paddingBottom="18dip" />

</RelativeLayout>

踩到的坑:兩個配置不能共用同一個 id

我原本想偷懶,讓兩份配置共用 chatlist_image 與 chatlist_text 這兩個 id,這樣 Adapter 裡就不用分兩套 id 陣列。測試下來完全行不通,畫面會出現嚴重的错位。

原因在於 ListView 繪製時會反覆呼叫 findViewById(),而這個方法是「在該 View 的子樹中找第一個符合 id 的節點」。共用 id 之後,getView 拿到的是哪一份配置、findViewById 又找到哪一個節點,兩者之間沒有任何保證,於是就出現了「頭像的位置配到文字」這類錯亂。結論很明確:不同用途的配置一定要用不同 id,這不是風格問題而是正確性問題。

ChatActivity

package com.example.android_qqfix;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ChatActivity extends Activity {

    private static final int ME    = 0;
    private static final int OTHER = 1;

    private ArrayList<HashMap<String, Object>> chatList = null;
    private String[] from = {"image", "text"};
    private int[] to = {R.id.chatlist_image_me, R.id.chatlist_text_me,
                        R.id.chatlist_image_other, R.id.chatlist_text_other};
    private int[] layout = {R.layout.chat_listitem_me, R.layout.chat_listitem_other};

    protected ListView chatListView = null;
    protected Button   chatSendButton = null;
    protected EditText editText = null;
    protected MyChatAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_chat);

        chatList = new ArrayList<HashMap<String, Object>>();
        addTextToList("不管你是誰", ME);
        addTextToList("群發的我不回 ^_^", OTHER);
        addTextToList("哈哈哈哈", ME);
        addTextToList("新年快樂!", OTHER);

        chatSendButton = (Button) findViewById(R.id.chat_bottom_sendbutton);
        editText       = (EditText) findViewById(R.id.chat_bottom_edittext);
        chatListView   = (ListView) findViewById(R.id.chat_list);

        adapter = new MyChatAdapter(this, chatList, layout, from, to);

        chatSendButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 加上 "" 是為了避免 getText() 回傳 null 時 toString() 拋例外
                String myWord = (editText.getText() + "").toString();
                if (myWord.length() == 0) return;

                editText.setText("");
                addTextToList(myWord, ME);

                adapter.notifyDataSetChanged();
                // 讓列表永遠停在最底端
                chatListView.setSelection(chatList.size() - 1);
            }
        });

        chatListView.setAdapter(adapter);
    }

    protected void addTextToList(String text, int who) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("person", who);
        map.put("image", who == ME ? R.drawable.contact_0 : R.drawable.contact_1);
        map.put("text", text);
        chatList.add(map);
    }

    private class MyChatAdapter extends BaseAdapter {

        private Context context;
        private ArrayList<HashMap<String, Object>> chatList;
        private int[] layout;
        private String[] from;
        private int[] to;

        public MyChatAdapter(Context context,
                             ArrayList<HashMap<String, Object>> chatList,
                             int[] layout, String[] from, int[] to) {
            this.context = context;
            this.chatList = chatList;
            this.layout = layout;
            this.from = from;
            this.to = to;
        }

        @Override
        public int getCount() {
            return chatList.size();
        }

        @Override
        public Object getItem(int position) {
            return chatList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        class ViewHolder {
            ImageView imageView;
            TextView  textView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            int who = (Integer) chatList.get(position).get("person");

            // 依訊息來源挑選對應的項目配置
            convertView = LayoutInflater.from(context)
                    .inflate(layout[who == ME ? 0 : 1], null);

            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(to[who * 2 + 0]);
            holder.textView  = (TextView)  convertView.findViewById(to[who * 2 + 1]);

            holder.imageView.setBackgroundResource(
                    (Integer) chatList.get(position).get(from[0]));
            holder.textView.setText(
                    chatList.get(position).get(from[1]).toString());

            return convertView;
        }
    }
}

這個版本可以更好的地方

這份程式能跑、能看懂,但仍有幾處值得改進:

getView 沒有複用 convertView。每次捲動都重新 inflate 一份配置,訊息一多就會明顯卡頓。正確做法是判斷 convertView 是否為 null,不為 null 就直接重用並只更新內容。

沒有區分 view type。更道地的做法是覆寫 getItemViewType() 與 getViewTypeCount(),讓 ListView 自己知道有兩種項目、並為兩種型別各自維護回收池。這樣效能與正確性都更好。

用 HashMap 傳資料太鬆散。key 打錯字不會編譯報錯,只會在執行期安靜地拿到 null。改用一個正式的 POJO(例如 ChatMessage{ int who; String text; int avatar; })會安全得多。

不要把資料寫死在 onCreate 裡。範例中那四則訊息只是為了看效果。真實場景應該從資料庫或 Socket 讀取,並在背景執行緒處理。

若今天重寫這個介面,我會直接用 RecyclerView 搭配兩個 ViewHolder,並用 DiffUtil 處理資料更新。但作為理解 ListView 多項目配置的入門練習,把底層原理走過一遍還是很值得的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved