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

仿微信聊天氣泡效果實作教學

編輯:關於 Android 程式設計

微信聊天視窗的訊息呈現方式類似 iPhone 上的簡訊,以氣泡形式展示。在 Android 上實作這種效果,主要會用到 ListView 與 BaseAdapter,再搭配適當的布局與素材即可。素材部分可以下載微信的 APK,將副檔名改成 zip 後解壓,就能取得其中所有圖形資源。

整體思路

整個畫面由上、中、下三部分組成:頂部標題列、中間的訊息列表(ListView)、底部的輸入區。訊息列表裡有兩種 item:一種是接收訊息的氣泡(靠左),另一種是發送訊息的氣泡(靠右)。透過 Adapter 的 getItemViewType() 與 getViewTypeCount() 來區分兩種樣式。

主布局 main.xml

<?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_top"
        android:layout_width="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="44dp"
            android:gravity="center"
            android:textSize="18sp"
            android:background="#486a9a"
            android:textColor="@android:color/white"
            android:text="Chat"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rl_bottom"
        android:layout_alignParentBottom="true"
        android:layout_width="fill_parent"
        android:background="#486a9a"
        android:paddingTop="5dp"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btn_send"
            android:layout_width="70dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:text="Send" />
        <EditText
            android:id="@+id/et_content"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toLeftOf="@id/btn_send"
            android:textSize="16sp"/>
    </RelativeLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/rl_bottom"
        android:layout_below="@id/rl_top"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:cacheColorHint="#00000000"
        android:divider="@null"
        android:listSelector="#00000000"
        android:dividerHeight="3dp"
        android:scrollbars="none"/>
</RelativeLayout>

接收訊息的 item 布局 chat_from_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="#bfbfbf"
        android:paddingTop="2dp"
        android:paddingBottom="2dp"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:textColor="#ffffff"
        android:textSize="12sp" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp" >
        <ImageView
            android:id="@+id/iv_user_image"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/mypic"
            android:focusable="false" />
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/iv_user_image"
            android:background="@drawable/chatfrom_bg"
            android:gravity="left|center"
            android:clickable="true"
            android:focusable="true"
            android:lineSpacingExtra="2dp"
            android:minHeight="50dp"
            android:textColor="#ff000000"
            android:textSize="14sp" />
    </RelativeLayout>
</LinearLayout>

發送訊息的 item 布局 chat_to_item.xml

結構與接收版類似,主要差異是頭像靠右、氣泡在頭像左側並使用 chatto_bg 背景:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#bfbfbf"
        android:layout_gravity="center_horizontal"
        android:paddingTop="2dp"
        android:paddingBottom="2dp"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:textColor="#ffffff"
        android:textSize="12sp" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp" >
        <ImageView
            android:id="@+id/iv_user_image"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/mypic"
            android:focusable="false" />
        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@+id/iv_user_image"
            android:background="@drawable/chatto_bg"
            android:gravity="left|center"
            android:clickable="true"
            android:focusable="true"
            android:lineSpacingExtra="2dp"
            android:textColor="#ff000000"
            android:textSize="14sp" />
    </RelativeLayout>
</LinearLayout>

資料實體類 ChatEntity.java

public class ChatEntity {
    private int userImage;
    private String content;
    private String chatTime;
    private boolean isComeMsg; // true 表示接收,false 表示發送

    public int getUserImage() { return userImage; }
    public void setUserImage(int userImage) { this.userImage = userImage; }
    public String getContent() { return content; }
    public void setContent(String content) { this.content = content; }
    public String getChatTime() { return chatTime; }
    public void setChatTime(String chatTime) { this.chatTime = chatTime; }
    public boolean isComeMsg() { return isComeMsg; }
    public void setComeMsg(boolean isComeMsg) { this.isComeMsg = isComeMsg; }
}

主 Activity 與自訂 Adapter

核心在於 ChatAdapter 繼承 BaseAdapter,透過 getItemViewType() 回傳不同的 view 類型,並在 getView() 中依類型載入對應布局:

public class ChatDemoActivity extends Activity {
    private Button sendButton = null;
    private EditText contentEditText = null;
    private ListView chatListView = null;
    private List<ChatEntity> chatList = null;
    private ChatAdapter chatAdapter = null;

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

        contentEditText = (EditText) this.findViewById(R.id.et_content);
        sendButton = (Button) this.findViewById(R.id.btn_send);
        chatListView = (ListView) this.findViewById(R.id.listview);

        chatList = new ArrayList<ChatEntity>();
        ChatEntity chatEntity = null;
        for (int i = 0; i < 2; i++) {
            chatEntity = new ChatEntity();
            if (i % 2 == 0) {
                chatEntity.setComeMsg(false);
                chatEntity.setContent("Hello");
                chatEntity.setChatTime("2012-09-20 15:12:32");
            } else {
                chatEntity.setComeMsg(true);
                chatEntity.setContent("Hello, nice to meet you!");
                chatEntity.setChatTime("2012-09-20 15:13:32");
            }
            chatList.add(chatEntity);
        }

        chatAdapter = new ChatAdapter(this, chatList);
        chatListView.setAdapter(chatAdapter);

        sendButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!contentEditText.getText().toString().equals("")) {
                    send();
                } else {
                    Toast.makeText(ChatDemoActivity.this, "Content is empty",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void send() {
        ChatEntity chatEntity = new ChatEntity();
        chatEntity.setChatTime("2012-09-20 15:16:34");
        chatEntity.setContent(contentEditText.getText().toString());
        chatEntity.setComeMsg(false);
        chatList.add(chatEntity);
        chatAdapter.notifyDataSetChanged();
        chatListView.setSelection(chatList.size() - 1);
        contentEditText.setText("");
    }

    private class ChatAdapter extends BaseAdapter {
        private Context context = null;
        private List<ChatEntity> chatList = null;
        private LayoutInflater inflater = null;
        private int COME_MSG = 0;
        private int TO_MSG = 1;

        public ChatAdapter(Context context, List<ChatEntity> chatList) {
            this.context = context;
            this.chatList = chatList;
            inflater = LayoutInflater.from(this.context);
        }

        @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; }

        @Override
        public int getItemViewType(int position) {
            // 依是否為接收訊息,回傳不同的 view 類型
            ChatEntity entity = chatList.get(position);
            if (entity.isComeMsg()) {
                return COME_MSG;
            } else {
                return TO_MSG;
            }
        }

        @Override
        public int getViewTypeCount() {
            return 2; // 有兩種風格
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ChatHolder chatHolder = null;
            if (convertView == null) {
                chatHolder = new ChatHolder();
                if (chatList.get(position).isComeMsg()) {
                    convertView = inflater.inflate(R.layout.chat_from_item, null);
                } else {
                    convertView = inflater.inflate(R.layout.chat_to_item, null);
                }
                chatHolder.timeTextView = (TextView) convertView.findViewById(R.id.tv_time);
                chatHolder.contentTextView = (TextView) convertView.findViewById(R.id.tv_content);
                chatHolder.userImageView = (ImageView) convertView.findViewById(R.id.iv_user_image);
                convertView.setTag(chatHolder);
            } else {
                chatHolder = (ChatHolder) convertView.getTag();
            }

            chatHolder.timeTextView.setText(chatList.get(position).getChatTime());
            chatHolder.contentTextView.setText(chatList.get(position).getContent());
            chatHolder.userImageView.setImageResource(chatList.get(position).getUserImage());
            return convertView;
        }

        private class ChatHolder {
            private TextView timeTextView;
            private ImageView userImageView;
            private TextView contentTextView;
        }
    }
}

實作重點在於:用一個 boolean 欄位標記訊息方向,Adapter 依此切換兩種布局,並用 ChatHolder(即 ViewHolder 模式)快取子 View 以提升列表滾動效能。掌握這個骨架後,就能輕鬆做出與微信相仿的聊天气泡介面。

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