今天改一下主聊天介面的格式,使它成為按條列分佈的格式
package com.example.helppeople.adapter; 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 com.example.helppeople.R; import com.example.helppeople.entity.ChatBean; import java.util.List; public class ChatAdapter extends BaseAdapter { private List<ChatBean> chatBeanList;//聊天資料 private LayoutInflater layoutInflater; private static final int VIEW_TYPE_RECEIVE = 0; private static final int VIEW_TYPE_SEND = 1; public ChatAdapter(List<ChatBean> chatBeanList, Context context) { this.chatBeanList = chatBeanList; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return chatBeanList.size(); } @Override public Object getItem(int position) { return chatBeanList.get(position); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 2; // 兩種型別的佈局:接收和傳送 } @Override public int getItemViewType(int position) { if (chatBeanList.get(position).getState() == ChatBean.RECEIVE) { return VIEW_TYPE_RECEIVE; } else { return VIEW_TYPE_SEND; } } @Override public View getView(int position, View convertView, ViewGroup parent) { Holder holder; int viewType = getItemViewType(position); if (convertView == null) { holder = new Holder(); if (viewType == VIEW_TYPE_RECEIVE) { convertView = layoutInflater.inflate(R.layout.chatting_left_item, parent, false); } else { convertView = layoutInflater.inflate(R.layout.chatting_right_item, parent, false); } holder.tv_chat_content = convertView.findViewById(R.id.tv_chat_content); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } holder.tv_chat_content.setText(chatBeanList.get(position).getMessage()); return convertView; } class Holder { TextView tv_chat_content;//聊天內容 } }