07/08/2021 RecyclerViews & Card View | Alexandria
MODULE
RecyclerViews & Card View
Nawfal Ali
Updated 22 April 2020
What is RecyclerView?
A RecyclerView is a exible viewgroup for providing a limited window into a large data set. The purpose of the RecyclerView is to allow information to be presented to the user in the form of a scrollable list. The RecyclerView is signi cantly more e cient in the way it manages the views that make up a list, essentially reusing existing views that make up list items as they scroll o the screen instead if creating new ones (hence the name “recycler”).
Random Card Generator Application
In the following sections, we are going to develop an application that uses RecyclerView to display Cards that are generated randomly. Each card is implemented as a CardView.
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 1/12
07/08/2021 RecyclerViews & Card View | Alexandria
CardView
The CardView class is a user interface view that allows information to be presented in groups using a card metaphor. Cards are usually presented in lists using a RecyclerView instance and may be con gured to appear with shadow e ects and rounded corners.
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 2/12
07/08/2021 RecyclerViews & Card View | Alexandria
https://
3/12
The user interface layout to be presented with a CardView instance is de ned within an XML layout resource le and loaded into the CardView at runtime. The CardView layout can contain a layout of any complexity using the standard layout managers such as RelativeLayout and LinearLayout.
card_layout.xml
1.
2.
10.
11.
15. 16.
17.
26.
www.alexandriarepository.org/module/recyclerviews-card-view/
07/08/2
https://
021 RecyclerViews & Card View | Alexandria
4/12
27.
36.
37.
38.
As you can see, the cardview works as a top-level container that has a relative layout as a child element. Inside the relative layout, we have two text views that will be used to display our data. You can replace the relative layout with any layout you do prefer.
RecyclerView
It is a container for rendering a larger data set of views that can be recycled and scrolled very e ciently. It uses a subclass of RecyclerView.Adapter for providing views that represent items in a data set.
activity_main.xml
1.
2.
www.alexandriarepository.org/module/recyclerviews-card-view/
07/08/2
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 5/12
021 RecyclerViews & Card View | Alexandria
8.
9.
15.
16.
25.
26.
39.
07/08/2021 RecyclerViews & Card View | Alexandria
The code provided above represents the layout le of the main activity. It uses constraint layout as the main container (@line2). The horizontal guideline is used to separate the button from the recycler view.
Item.java
1. 2. 3. 4. 5.
6. 7. 8.
9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.
packagecom.fit2081.recyclercard; publicclassItem{
private String suit;
private String card;
public Item(String suit, String card) { this.suit = suit;
this.card = card;
}
public String getSuit() { return suit;
}
public String getCard() { return card;
} }
Each card consists of a suit and a card number. Item.java is a class that works as a record for one card. Later in the code, we will create an array list of cards using this class. The constructor is used to initialize the two instance variables while the two getters are used to retrieve their values.
RecyclerView.Adapter
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 6/12
07/08/2021 RecyclerViews & Card View | Alexandria
https://
7/12
The adapter is created as a subclass of the RecyclerView.Adapter class and must, at a minimum, implement the following methods, which will be called at various points by the RecyclerView object to which the adapter is assigned:
getItemCount() – This method must return a count of the number of items that are to be displayed in the list.
onCreateViewHolder() – This method creates and returns a ViewHolder object initialized with the view that is to be used to display the data. This view is typically created by in ating the XML layout le. onBindViewHolder() – This method is passed the ViewHolder object created by the onCreateViewHolder() method together with an integer value indicating the list item that is about to be displayed. Contained within the ViewHolder object is the layout assigned by the onCreateViewHolder() method. It is the responsibility of the onBindViewHolder() method to populate the views in the layout with the text and graphics corresponding to the speci ed item and to return the object to the RecyclerView where it will be presented to the user.
MyRecyclerAdapter.java
1. packagecom.fit2081.recyclercard; 2.
3. importandroid.util.Log;
4. importandroid.view.LayoutInflater;
5. importandroid.view.View;
6. import android.view.ViewGroup;
7. importandroid.widget.TextView;
8.
9. import androidx.annotation.NonNull;
10. importandroidx.recyclerview.widget.RecyclerView;
11.
12. importjava.util.ArrayList;
13.
14. publicclassMyRecyclerAdapterextends
RecyclerView.Adapter
www.alexandriarepository.org/module/recyclerviews-card-view/
07/08/2
https://
021 RecyclerViews & Card View | Alexandria
15. 16. 17. 18. 19.
20. 21. 22. 23. 24.
25.
26. 27. 28. 29. 30.
31. 32.
33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44.
ArrayList
public void setData(ArrayList
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout,
parent, false); //CardView inflated as RecyclerView list item
ViewHolder viewHolder = new ViewHolder(v); Log.d(“week6App”,”onCreateViewHolder”); return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.cardTv.setText(data.get(position).getCard());
holder.suitTv.setText(data.get(position).getSuit());
Log.d(“week6App”,”onBindViewHolder”);
}
@Override
public int getItemCount() { return data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
www.alexandriarepository.org/module/recyclerviews-card-view/
8/12
07/08/2
https://
021 RecyclerViews & Card View | Alexandria
9/12
45. 46. 47. 48. 49. 50.
51. 52. 53. 54.
public TextView suitTv;
public TextView cardTv;
public ViewHolder(@NonNull View itemView) { super(itemView);
suitTv = itemView.findViewById(R.id.suit_id);
cardTv = itemView.findViewById(R.id.card_id);
}
} }
The code provided is the implementation of the RecyclerAdapter. It implements the three methods mentioned earlier and the ViewHolder subclass (@line44). The data is passed to the adaptor through a method called setData (@line18) which is called from the MainActivity.java (@line44). The method getItemCount (@line40) returns the size of the array list which is the number of items to be displayed in the list. The
method onCreateViewHolder in ates the card’s layout that we have implemented earlier each time a new card is required (@line25). It the passes v, which is a reference to the card layout to the contractor of ViewHolder local class. At line 28, the method returns the view holder object that will be an input to the next method onBindViewHolder. In the latter method, we receive two parameters, a viewer holder and a position. Our job is to retrieve the data at that position and place it in that view holder.
MainActivity.java
1. packagecom.fit2081.recyclercard; 2.
3. importandroidx.appcompat.app.AppCompatActivity;
4. importandroidx.recyclerview.widget.LinearLayoutManager;
5. importandroidx.recyclerview.widget.RecyclerView;
6.
7. importandroid.os.Bundle;
8. importandroid.view.View;
9. import android.widget.Button;
www.alexandriarepository.org/module/recyclerviews-card-view/
07/08/2
https://
021 RecyclerViews & Card View | Alexandria
10. 11. 12. 13. 14. 15. 16. 17. 18.
importjava.util.ArrayList; importjava.util.Random;
publicclassMainActivityextendsAppCompatActivity{
ArrayList
String suits[] = {“Hearts”, “Diamonds”, “Clubs”, “Spade”}; String cards[] = {“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”,
“Jack”, “Queen”, “King”, “Ace”}; 19.
20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39.
Button btn;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
MyRecyclerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
btn = findViewById(R.id.add_item); btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { addItem();
} });
recyclerView = findViewById(R.id.my_recycler_view);
layoutManager = new LinearLayoutManager(this); //A RecyclerView.LayoutManager implementation which provides similar functionality to ListView.
www.alexandriarepository.org/module/recyclerviews-card-view/
10/12
07/08/2
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 11/12
021 RecyclerViews & Card View | Alexandria
40.
41. 42. 43. 44. 45. 46. 47. 48. 49. 50.
51. 52. 53. 54. 55. 56. 57. 58. 59.
recyclerView.setLayoutManager(layoutManager); // Also
StaggeredGridLayoutManager and GridLayoutManager or a custom Layout
manager
adapter = new MyRecyclerAdapter(); adapter.setData(data); recyclerView.setAdapter(adapter);
}
public void addItem() {
Random random = new Random();
int randCard = random.nextInt(cards.length);
int randSuit = random.nextInt(suits.length);
Item item = new Item(suits[randSuit], cards[randCard]); data.add(item);
adapter.notifyDataSetChanged();
} }
In the code above, we have created three entities, a recycler view (@line37), dataset (@line16), and an adapter (@line43). The adapter works as a bridge between the recyclerview and the dataset (@line43,44).
Each time the data gets changed, you should notify the adapter by calling adapter.notifyDataSetChanged() in order to update the recycler view (i.e. the UI)
References:
07/08/2021 RecyclerViews & Card View | Alexandria
Smyth, Neil. Android Studio 3.5 Development Essentials – Java Edition: Developing Android 10 (Q) Apps Using Android Studio 3.5, Java and Android Jetpack . Payload Media, Inc.. Kindle Edition. https://developer.android.com/
Copyright © Monash University, unless otherwise stated. All Rights Reserved, except for individual components (or items) marked with their own licence restrictions
Copyright © 2021 Monash University, unless otherwise stated
Disclaimer and Copyright Privacy
Service Status
https://www.alexandriarepository.org/module/recyclerviews-card-view/ 12/12