編輯:關於 Android 開發
本文說明如何以 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 需要依訊息來源決定使用哪一個項目配置。可透過 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 的聊天效果。
自定義 View 與觸控事件:讓圖形跟著手指移動
要做的事 這個範例示範一個很基礎但很常被問到的題目:畫一個圓,手指按在畫面上拖到哪裡,圓就跟到哪裡。牽涉到的知識點有三個——自定義 View、OnTouchListene
團隊專案週報(4.20):Android Studio 上手與预算管理模組規劃
本週完成情況:熟悉 Android Studio 的操作介面與基礎功能,並擬定個人負責模組的初步計畫。 學習紀錄: 跑通 Hello World:https://jing
Android加固教程:先學會破解,用IDA動態調試修改內存改寫程式走向
Android加固教程:先學會破解,用IDA動態調試修改內存改寫程式走向 【版權所有,轉載請註明出處。】 因公司專案需要對app進行加固,經過數月研究,我實現了一套完整的
一次搞懂 Android 動畫:四大類型與 XML/Java 雙寫法
讓介面「動」起來的 Android 動畫 好的動畫能讓操作回饋更直覺、畫面過渡更順暢。在 Android 中,動畫主要由四大類型構成,而實作方式又可歸納為兩種模式。本文將