![]() |
VOOZH | about |
A nested RecyclerView is an implementation of a RecyclerView within a RecyclerView. An example of such a layout can be seen in a variety of apps such as the Play Store, where the outer (parent) RecyclerView is of vertical orientation, whereas the inner (child) RecyclerViews are of horizontal orientation. A similar layout is developed here.
Add the following dependencies to the build. gradle file. The first dependency corresponds to RecyclerView and is mandatory. The second one is for CardView, which is optional depending on the UI requirements. Since CardView is used in the child RecyclerView layout here, the CardView dependency is added.
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
Note: For the correct versions of dependencies check here.
The parent RecyclerView is implemented in the activity_main file. Here, activity_main file only holds the parent RecyclerView, but it can be customized as per the requirements.
Identify requirements for the parent layout and add Views corresponding to them in an XML layout file. Here, layout files are named as parent_item. In addition to the child RecyclerView, a TextView for the title is included.
The layout of the items of the child RecyclerView is created in an XML layout file named child_item. Child RecyclerView includes an ImageView and a TextView, both wrapped inside a CardView.
The following image is used as the resource of the ImageView, thus it is added in the drawable resource folder.
A Java class is required for each RecyclerView wherein the constructor initializes the parameters of the item and the getter and setter methods are declared. Thus, create the following Java classes:
An adapter class is required to pass the data that is to be displayed in the views of RecyclerView. An adapter class is needed for the ChildItem as well as ParentItem classes.
In the ParentItemAdapter class, an instance of the class is created
RecyclerView.RecycledViewPool
This class is used to pass Views between the parent RecyclerView and the child RecyclerView.
Step 7: Set the layout of parent RecyclerView and pass the arguments to both the RecyclerViews. The arguments to be passed to the RecyclerViews are given in the Java class that inflates the activity of the parent RecyclerView (here activity_main). So here the arguments will be passed in the MainActivity file.
Also, set the layout for the parent RecyclerView here itself.
Output: