編輯:關於 Android 程式設計
微信的氣泡聊天靈感來自 iPhone 內建簡訊,但實際做出來的質感相當好。本文拆解一個可運作的 Demo:以 ListView 承載對話清單,用 9-patch 圖片讓氣泡能隨內容長度自由伸縮,並透過自訂 Adapter 區分「對方傳來」與「自己送出」兩種版面。
氣泡聊天最關鍵的不是程式碼,而是素材。這裡使用的是 .9.png 格式的九宮格圖片:它在 PNG 邊界多留了 1px 的黑線,標示出「哪四個角不能拉伸」與「哪兩段區域可以重複延展」。因此無論一行短句還是十行長文,氣泡都能自動撐開而四角與箭頭不會變形。若直接用普通 PNG,內容一長邊框就會被拉爛。
Demo 中的素材是從微信直接擷取的,實作時請替換成自己擁有的圖片資源。
先把一則訊息 needed 的資訊封裝成物件。這裡有個設計重點:isComMeg 這個布林值決定氣泡要顯示在左邊還是右邊,是整個 Adapter 分支的依據。
package com.example.school;
public class ChatMsgEntity {
private static final String TAG = ChatMsgEntity.class.getSimpleName();
private String name; // 名字
private String date; // 日期時間
private String text; // 聊天內容
private boolean isComMeg = true; // 是否為對方傳來的消息
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean getMsgType() {
return isComMeg;
}
public void setMsgType(boolean isComMsg) {
isComMeg = isComMsg;
}
public ChatMsgEntity() {
}
public ChatMsgEntity(String name, String date, String text, boolean isComMsg) {
this.name = name;
this.date = date;
this.text = text;
this.isComMeg = isComMsg;
}
}
這個 Adapter 有兩個關鍵設計。第一是覆寫 getItemViewType() 與 getViewTypeCount(),告訴 ListView「清單裡有兩種項目」。少了這一步,ListView 的快取機制會把左氣泡的 View 回收拿去給右氣泡用,導致版面錯亂。第二是 ViewHolder 模式,把 findViewById 的結果快取下來,避免每次捲動都重複查詢視圖樹。
package com.example.school;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ChatMsgViewAdapter extends BaseAdapter {
// ListView 項目的兩種類型
public static interface IMsgViewType {
int IMVT_COM_MSG = 0; // 對方傳來
int IMVT_TO_MSG = 1; // 自己發出
}
private static final String TAG = ChatMsgViewAdapter.class.getSimpleName();
private List<ChatMsgEntity> data;
private Context context;
private LayoutInflater mInflater;
public ChatMsgViewAdapter(Context context, List<ChatMsgEntity> data) {
this.context = context;
this.data = data;
mInflater = LayoutInflater.from(context);
}
// 項目數量
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
// 決定這個位置要哪一種版面
@Override
public int getItemViewType(int position) {
ChatMsgEntity entity = data.get(position);
if (entity.getMsgType()) {
return IMsgViewType.IMVT_COM_MSG;
} else {
return IMsgViewType.IMVT_TO_MSG;
}
}
// 必須回報總共有幾種版面,否則 ListView 無法正確區分快取
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMsgEntity entity = data.get(position);
boolean isComMsg = entity.getMsgType();
ViewHolder viewHolder = null;
if (convertView == null) {
if (isComMsg) {
// 對方傳來的訊息:左氣泡
convertView = mInflater.inflate(R.layout.chatting_item_msg_text_left, null);
} else {
// 自己發出的訊息:右氣泡
convertView = mInflater.inflate(R.layout.chatting_item_msg_text_right, null);
}
viewHolder = new ViewHolder();
viewHolder.tvSendTime = (TextView) convertView.findViewById(R.id.tv_sendtime);
viewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_username);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_chatcontent);
viewHolder.isComMsg = isComMsg;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvSendTime.setText(entity.getDate());
viewHolder.tvUserName.setText(entity.getName());
viewHolder.tvContent.setText(entity.getText());
return convertView;
}
// 透過 ViewHolder 快取各項目的子視圖
static class ViewHolder {
public TextView tvSendTime;
public TextView tvUserName;
public TextView tvContent;
public boolean isComMsg = true;
}
}
結構是「上方置中的時間戳 + 下方 RelativeLayout(頭像在左、氣泡在右、名字在頭像底下)」。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:id="@+id/tv_sendtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/chat_text_date_style"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" >
<ImageView
android:id="@+id/iv_userhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/mini_avatar_shadow"/>
<TextView
android:id="@+id/tv_chatcontent"
android:layout_toRightOf="@id/iv_userhead"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/chatfrom_bg"
style="@style/chat_content_date_style"/>
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/iv_userhead"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/tv_chatcontent"
style="@style/chat_text_name_style"/>
</RelativeLayout>
</LinearLayout>
chatting_item_msg_text_right.xml 與它幾乎相同,差別只在氣泡與頭像左右對調:android:layout_alignParentRight 取代 Left,氣泡改用 layout_toLeftOf,背景換成右向箭頭的 9-patch 圖。這裡不重複貼上。
值得注意的是氣泡那個 TextView 用了 wrap_content 寬高——正是這個設定搭配 9-patch 背景,才能讓氣泡隨文字長度自動伸展。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0e0" >
<!-- 標題列 -->
<RelativeLayout
android:id="@+id/rl_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title" >
<Button
android:id="@+id/btn_back"
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:paddingLeft="18dp"
android:textSize="18.0sp"
android:textColor="#ffffff"
android:background="@drawable/selector_btn_back"
android:text="@string/back" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/school_title_name"
android:layout_centerInParent="true"
style="@style/my_txt"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/campus_info"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"/>
</RelativeLayout>
<!-- 對話清單:夾在標題列與輸入列之間 -->
<ListView
android:id="@+id/listview"
android:layout_below="@id/rl_layout"
android:layout_above="@id/rl_bottom"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10.0dip"
android:layout_marginTop="10.0dip"
android:layout_marginRight="10.0dip"
android:divider="@null"
android:dividerHeight="5dp"
android:scrollbars="none"
android:cacheColorHint="#00000000"/>
<!-- 底部輸入列 -->
<RelativeLayout
android:id="@+id/rl_bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/layout_bg1" >
<Button
android:id="@+id/btn_send"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:text="@string/send" />
<EditText
android:id="@+id/et_sendmessage"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_toLeftOf="@id/btn_send"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_centerVertical="true"
android:background="@drawable/edittext1"
android:singleLine="true"
android:textSize="18sp"/>
</RelativeLayout>
</RelativeLayout>
用 RelativeLayout 把「標題列固定上方、輸入列固定下方、ListView 填滿中間」的結構一次描述完,是聊天畫面最乾淨的寫法。android:divider="@null" 拿掉了系統預設的分隔線——氣泡之間本來就該留白,多一條線反而突兀。
package com.example.chat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.example.school.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ChatActivity extends Activity implements OnClickListener {
private Button mBtnSend;
private Button mBtnBack;
private EditText mEditTextContent;
private ChatMsgViewAdapter mAdapter;
private ListView mListView;
// 聊天內容
private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉標題列
setContentView(R.layout.chat);
initView();
initData();
}
// 初始化視圖
private void initView() {
mListView = (ListView) findViewById(R.id.listview);
mBtnBack = (Button) findViewById(R.id.btn_back);
mBtnBack.setOnClickListener(this);
mBtnSend = (Button) findViewById(R.id.btn_send);
mBtnSend.setOnClickListener(this);
mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
}
private String[] msgArray = new String[]{
"孩子們,要好好學習,天天向上!要好好聽課,不要翹課!不要掛科,多拿獎學金!",
"姚媽媽還有什麼吩咐...",
"還有,明天早上記得跑操啊,不來的就扣德育分!",
"德育分是什麼?扣了會怎麼樣?",
"德育分會影響獎學金評比,嚴重的話,會影響畢業",
"哇!學院那麼不人道?",
"你要是你不聽話,我當場讓你不能畢業!",
"姚媽媽,我知錯了(- -我錯在哪了...)"};
private String[] dataArray = new String[]{
"2012-09-01 18:00", "2012-09-01 18:10",
"2012-09-01 18:11", "2012-09-01 18:20",
"2012-09-01 18:30", "2012-09-01 18:35",
"2012-09-01 18:40", "2012-09-01 18:50"};
private final static int COUNT = 8;
// 初始化要顯示的假資料
private void initData() {
for (int i = 0; i < COUNT; i++) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(dataArray[i]);
if (i % 2 == 0) {
entity.setName("姚媽媽");
entity.setMsgType(true); // 左氣泡
} else {
entity.setName("Shamoo");
entity.setMsgType(false); // 右氣泡
}
entity.setText(msgArray[i]);
mDataArrays.add(entity);
}
mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
mListView.setAdapter(mAdapter);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_back:
back();
break;
case R.id.btn_send:
send();
break;
}
}
private void send() {
String contString = mEditTextContent.getText().toString();
if (contString.length() > 0) {
ChatMsgEntity entity = new ChatMsgEntity();
entity.setDate(getDate());
entity.setName("");
entity.setMsgType(false); // 自己發出的走右氣泡
entity.setText(contString);
mDataArrays.add(entity);
mAdapter.notifyDataSetChanged();
mEditTextContent.setText("");
// 捲到最底,讓最新訊息保持可見
mListView.setSelection(mListView.getCount() - 1);
}
}
// 取得目前日期時間
private String getDate() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH) + 1);
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mins = String.valueOf(c.get(Calendar.MINUTE));
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins);
return sbBuffer.toString();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
back();
return true;
}
private void back() {
finish();
}
}
這裡順手修掉了原範例 getDate() 中的兩個小 bug:Calendar.MONTH 是從 0 開始計算的,要 +1 才是人類看得懂的月份;DAY_OF_MONTH 本身就是正確的日期,不該再 +1。
在 AndroidManifest.xml 對應的 Activity 加上 android:windowSoftInputMode="adjustResize",清單才會隨鍵盤縮短,而不是被整個蓋住。
setSelection(getCount() - 1) 是硬捲到底。若想只在「使用者本來就在底部附近」時才自動捲動(避免干擾正在看歷史訊息的人),可以先判斷 getFirstVisiblePosition() 與 getLastVisiblePosition() 的距離再決定。
這個 Demo 用 ListView 是為了把「兩種項目型別 + ViewHolder」的觀念講清楚,這些概念在 RecyclerView 中完全通用,而且更好用。RecyclerView 內建了 DiffUtil 能做局部更新(不必每次 notifyDataSetChanged() 重繪整份清單)、內建 LayoutManager 與項目動畫、也更容易實作「新訊息插入時的滑入效果」。若是新專案,建議把同樣的結構搬到 RecyclerView 上:ChatMsgEntity 與兩種 ViewHolder 的設計可以原封不動沿用,只需把 Adapter 改成繼承 RecyclerView.Adapter 並用 notifyItemInserted() 取代全量刷新。
Demo 用寫死的陣列產生假資料,重開 App 對話就消失了。實作時應把訊息寫入 SQLite 或 Room,並在 onCreate() 中讀回;訊息量大的話還要考慮分頁載入,避免一次把全部歷史塞進記憶體。
Android 布局詳解:五大常用布局全面梳理
引言——概述 布局是不可見的容器(ViewGroup),用於定義 UI 的可視化結構,並透過布局參數(LayoutParams)定義子元素的尺寸與位置。 Android
深入理解 Android 事件分發機制
Android 事件分發機制是理解 UI 互動的核心。當使用者點擊螢幕時,系統會產生 ACTION_DOWN、ACTION_MOVE、ACTION_UP 等事件,並依序傳
Android 圖片自適應控件:.9.png 九宮格製作教學
要讓圖片能隨著控件尺寸自由伸縮又不變形,方法是把原本的 .png 轉成 .9.png 格式。.9.png 只是在副檔名前多了一個 .9,靠四邊的黑線標記「哪些區域可以拉伸
Android 源碼解析:從 setContentView 看 Activity 佈局載入機制
從 setContentView 開始Activity 初始化時,常會呼叫 setContentView 來載入 XML 佈局。這一行程式看似簡單,實際上會經過 Acti