Android RecyclerView with Different Child Layouts

recycler_view_hetrogeneous

Recyclerview gives us the real power to use different types of child rows depending on our need. What I mean is there might be the situation when you need to use different layouts with respect to different data or depending on your need with different positions i.e heterogenous structure.

If you have not visited previous RecyclerView tutorial for homogeneous layout I strongly recommend you to visit that first.

Here we are going to see an example of chat screen in which there are two different child layouts used to meet the need to separate the messages of sender and receiver.

Here we are considering sender and receiver both on the same screens (lol), differentiated with just the buttons they are going to use to send the message.

Steps:

  1. Import gradle dependency for recyclerview and design support library in build.gradle(Module:app).
  2. Insert recyclerview in the layout where we want heterogeneous list, and add a footer layout to implement two buttons to send and receive messages and a shared space to write message.
  3. Make two different child row that will be inflated in recyclerview
  4. Add some colors in colors.xml
  5. Create some drawables.
  6. Create style for buttons in footer layout of activity_main in step two.
  7. Create a model class which will contain data for the recyclerview child.
  8. Code the recycleview adapter.
  9. Assign adapter to our recyclerview.
  10. Run and see the chatting with yourself ย ๐Ÿ˜‰

As we start a new project we will have MainActivity.java and activity_main.xml without changing anything.

 

Step 1:

Open your build.gradle(Module: app) and add as following in dependencies:

After adding dependencies, the module looks like below

 

Step 2:

Now we need to insert recyclerview ย and footer layout in our activity_main.xml as shown below.

 

Step 3:

  • Make two different child row that will be inflated in recyclerview

received_message.xml

sent_message.xml

  • Add some colors in colors.xml

  • Create some drawables.

bg_received_message

bg_sent_message

rounded_edittext

  • Create style for buttons in footer layout in styles.xml.

 

Step 4:

Create a model class which will contain data for the recyclerview child. Here we have created MessageModel.java that contains three variables message, isSender (Where message is from), time.

 

Step 5:

Code the recycleview adapter.

 

Step 6:

Assign adapter to our recyclerview and set appropriate methods on recyclerview to arrange like chat. (MainActivity.java)

Step 7:

Run and chat with yourself ๐Ÿ˜‰

RecyclerView Heterogeneous

 

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *