我正在制作一个使用firebase作为后端的聊天应用程序。目前,我面临的问题是在RecyclerView中设置发送和接收消息的项目布局。当我对发送和接收消息使用相同的Item布局时,它工作得很好。但是我想把屏幕分成两部分,左边用来发送信息,右边用来接收信息。当制作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类
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);
}
}
您可以覆盖FirebaseRecyclerAdapter
的getItemViewType
来实现这一点:
// 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
是两个布局之一,如果这些布局有不同的内容,那么一些findViewById
调用将返回null。
您阅读https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView#prerequisite
另外,为了使用FirebaseRecyclerAdapter的少量代码,您可以扩展并仅提供视图的功能。其他的将由超类处理,如Firebase Query。
请注意模型布局,可以是-1,因为你正在重写onCreateViewHolder