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

Android 仿 QQ 聊天介面實作

編輯:關於 Android 開發

Android 仿 QQ 聊天介面實作

本文說明如何以 ListView 為基礎,實作左右氣泡的聊天介面。畫面主要由聊天訊息列表、輸入框與發送按鈕組成。

主畫面配置

聊天背景可使用 LinearLayout 或 RelativeLayout,內部放置 ListView。為了避免聊天畫面出現多餘分隔線,可將 divider 設為透明。

<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 需要兩種項目配置:左側代表對方訊息,右側代表本人訊息。氣泡背景建議使用 .9.png,避免縮放時變形。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/ivicon"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="top" />

    <TextView
        android:id="@+id/tvname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:padding="8dp" />
</LinearLayout>

資料模型

聊天訊息需要包含姓名、內容與是否為本人發送等欄位,可建立 PersonChat 類別來保存這些資料。

public class PersonChat {
    private int id;
    private String name;
    private String chatMessage;
    private boolean isMeSend;

    public boolean isMeSend() {
        return isMeSend;
    }

    public void setMeSend(boolean isMeSend) {
        this.isMeSend = isMeSend;
    }
}

Adapter 的關鍵

Adapter 需要依訊息來源決定使用哪一個項目配置。可透過 getItemViewType 與 getView 判斷 isMeSend,再載入對應的左右布局。

@Override
public int getItemViewType(int position) {
    PersonChat entity = lists.get(position);
    if (entity.isMeSend()) {
        return IMsgViewType.IMVT_TO_MSG;
    } else {
        return IMsgViewType.IMVT_COM_MSG;
    }
}

發送訊息

點擊發送按鈕後,將輸入內容建立為 PersonChat,加入資料集合,再呼叫 notifyDataSetChanged 更新 ListView,最後捲動至最新一筆。

整體重點在於:用同一個 ListView 呈現不同方向的氣泡,並透過 Adapter 判斷訊息來源,即可做出類似 QQ 的聊天效果。

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