我正在使用firebase作为后端制作聊天应用程序。 目前,我在设置用于在RecyclerView中发送和接收消息的项目布局时遇到问题。 当我为发送和接收消息使用相同的项目布局时,它完美地工作。 但是我想将屏幕分为两部分左侧用于发送消息,右侧用于接收消息。 制作FirebaseRecyclerAdapter对象时,我只能传递一个布局作为参数。我真的在努力解决这个问题。希望有人帮助我。
private void loadMessages() {
mAdapter = new FirebaseRecyclerAdapter<MessageToSend, NewMessageViewHolder>(
MessageToSend.class,
R.layout.single_message_new,
NewMessageViewHolder.class,
messageRef.child(sender).child(receiver)
) {
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void populateViewHolder(NewMessageViewHolder viewHolder, MessageToSend model, int position) {
if (sender.equals(model.getSender())) {
viewHolder.outMessage.setTextColor(getResources().getColor(R.color.darkGreen));
}
else {
viewHolder.outMessage.setTextColor(Color.BLACK);
//viewHolder.outMessage.setGravity(Gravity.RIGHT);
}
viewHolder.outMessage.setText(model.getMessage());
viewHolder.sender.setText(model.getSender());
}
};
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mAdapter.getItemCount();
int lastVisiblePosition = mLinearlayoutManager.findLastCompletelyVisibleItemPosition();
// If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
// to the bottom of the list to show the newly added message.
if (lastVisiblePosition == -1 ||
(positionStart >= (friendlyMessageCount - 1) && lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setLayoutManager(mLinearlayoutManager);
recyclerView.setAdapter(mAdapter);
}
ViewHolder Class
public static class InMessageViewHolder extends RecyclerView.ViewHolder{
TextView inMessage;
TextView receiver;
CircleImageView receiverImage;
public InMessageViewHolder(View itemView) {
super(itemView);
inMessage = (TextView) itemView.findViewById(R.id.textView11);
receiver = (TextView) itemView.findViewById(R.id.textView12);
}
}
答案 0 :(得分:2)
您可以覆盖getItemViewType
的{{1}}来实现此目的:
FirebaseRecyclerAdapter
这将导致 // Check if the item at position is sender
private boolean isSender(int position) {
sender.equals(getItem(position).getSender());
}
@Override
public int getItemViewType(int position) {
if (isSender(position)) {
return R.layout.my_sender_layout;
} else {
return R.layout.my_receiver_layout;
}
}
有条件地扩充布局。但是,您仍然只能拥有一个RecyclerAdapter
子类,因此您需要确保在实现ViewHolder
时,您的代码已准备好public MyViewHolder(View itemView)
成为两个布局之一,如果这些布局有不同的内容然后一些itemView
调用将返回null。
答案 1 :(得分:0)
您阅读https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView#prerequisite
此外,为了使用少量的FirebaseRecyclerAdapter代码,您可以扩展并提供仅供查看的功能。其他人会从Firebase Query等超级课程中得到关注。
请注意模型布局,当你覆盖onCreateViewHolder时,它可以是-1