我试图在我的应用程序中添加一个简单的聊天程序,该程序将显示用户输入到右侧的消息以及来自另一个用户(服务器)的消息到左侧。我知道我需要创建自己的customAdapter,但在看了几个教程后,我似乎仍然无法理解如何创建满足我要求的自己的适配器。我知道这可能听起来很愚蠢和缺乏经验但是如何解决这个问题的任何帮助都将非常感激。
答案 0 :(得分:0)
试试这个,并尝试搜索更多样本示例:
public class ChatArrayAdapter extends ArrayAdapter {
private EmojiconTextView chatText;
private List chatMessageList = new ArrayList();
private LinearLayout singleMessageContainer,backgroundLayout;
public void add(ChatMessage object) {
chatMessageList.add(object);
super.add(object);
}
public ChatArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.chatMessageList.size();
}
public ChatMessage getItem(int index) {
return (ChatMessage) this.chatMessageList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_main, parent, false);
}
singleMessageContainer = (LinearLayout) row.findViewById(R.id.singleMessageContainer);
backgroundLayout = (LinearLayout) row.findViewById(R.id.backgroundLayout);
ChatMessage chatMessageObj = getItem(position);
chatText = (EmojiconTextView) row.findViewById(R.id.singleMessage);
chatText.setText(chatMessageObj.message);
backgroundLayout.setBackgroundResource(chatMessageObj.left ? R.drawable.balloon_incoming_focused : R.drawable.balloon_outgoing_focused);
singleMessageContainer.setGravity(chatMessageObj.left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
}
在主要活动中:
ListView listView = (ListView)findViewById(R.id.lv);
chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), R.layout.activity_main);
listView.setAdapter(chatArrayAdapter);
这是ChatMessag
public class ChatMessage {
public boolean left;
public String message;
public ChatMessage(boolean left, String message) {
super();
this.left = left;
this.message = message;
}
}