So I want to make a chat app with the help of the Firebase API
but it seems that I can't change between layout for specific items (eg: Sent and received messages). I found a way but it's not efficient and this method is like this: I make 1 layout whit the model for Sent and Received message and after that I wold hide the Sent box if the message is received and hide the Received Box if the Message is sent I use this for my adapter:
mPostAdapterChat = new FirebaseRecyclerAdapter<Chat, ChatViewHolder>(
Chat.class,
R.layout.item_layout_chat,
ChatViewHolder.class,
mChatRef
)
So do you guys have some methods how can I use 2 layout and change between them for every item (eg Sent and received message) or do you know another way how can I do it better than using gone/visibile
You can actually do this:
1) In your chat class, identify which type of message it is: send or receive. Add an attribute or create a method like isSent()
to check if it's a send message or a receive message. I'll use an isSent()
method as an example.
2) Override the method getItemViewType
in your recycler view adapter and return an int representing the type (eg 0 for send and 1 for receive)
@Override
public int getItemViewType(int position) {
Chat chat = this.getItem(position);
if(chat.isSent()){
return 0;
}else{
return 1;
}
}
To get an item in your RecyclerViewAdapter
override getItem:
@Override
public Chat getItem(int pos) {
return super.getItem(getCount() - 1 - pos);
}
3) In your onCreateViewHolder
method you'll have access to the view type so you can simply inflate a different layout depending on the view type.
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case 0: //inflate and return view holder type 0
case 1: //inflate and return view holder type 1
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.