Original address: magdamiu.com/2020/12/29/…

By MAGDA MIU

Recycler View is a View Group that helps us display a list of scrollable elements. It is one of the most commonly used UI components in Android applications, including data sources, adapters, and Recycler View. In addition to displaying content, Recycler View can also effectively reuse views that scroll down from the screen by recycling views.

Summary of the component

  • Data sources – A list of objects that can be obtained from a local database, as the result of a HYPERtext Transfer protocol request, or even a list with some predefined values.

  • To access Recycler View, a scrolling list of list items, we must add dependencies to the Gradle file

  • Layout of a piece of data – XML file

  • The layout manager handles the organization of UI components in a view (there are three predefined ways to display items)

  • The view holder has view information that is used to display an item

  • The adapter connects data to Recycler View

  • Set the adapter to Recycler View and we’re done

Layout manager

  • All view groups have layout managers

  • Locate the Recycler View for projects

  • Reuse item views that are no longer visible to users

  • Built-in Layout managers include Linear Layout Manager, Grid Layout Manager, and Staggered Grid Layout Manager

  • For Recycler View, it expands Recycler View. Layout manager

The adapter

  • We are talking about applying the adapter design pattern as an intermediary between the source data and the view that we want to display

  • An adapter is an architectural design pattern that allows objects with incompatible interfaces to collaborate

  • Responsible for creating, updating, adding and removing items from the list

  • It assumes that the abstract class Recycler View is implemented. The adapter

View holder

  • The adapter is used to prepare an item view for each element in the data source

  • The layout of the project is specified in an XML resource file, which is like a 1:1 relationship between the view and elements in the list of objects provided as a data source

  • You can have clickable elements that are placed by the layout manager

  • We must implement the abstract class Recycler View. View holder

The implementation steps

  1. Get data by creating a new object class (data source)

  2. Add Recycler View dependencies to app/build.gradle file and add Recycler View to the layout

  3. Create the XML layout for the project

  4. Define the Layout Manager in the activity

  5. Expand Recycler View. Separate the view holder from the class

  6. Expand Recycler View. Separate the adapters in the class

  7. In the on Create activity, use the adapter and layout manager to Create Recycler View

To cover the implementation steps, we will display an E-mail list. Data sources are hard-coded, and right now we’re focused on learning how to use Recycler View.

Step 1: Get the data by creating a new object class (data source)

public class Email { private int id; private String fromName; private String subject; private String shortBody;

public Email(int id, String fromName, String subject, String shortBody) { this.id = id; this.fromName = fromName; this.subject = subject; this.shortBody = shortBody; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFromName() { return fromName; } public void setFromName(String fromName) { this.fromName = fromName; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getShortBody() { return shortBody; } public void setShortBody(String shortBody) { this.shortBody = shortBody; } @Override public String toString() { return "Email{" + "id='" + id + '\'' + ", fromName='" + fromName + '\'' + ", title='" + subject + '\'' + ", shortBody='" + shortBody + '\'' + '}'; }}Copy the code
private void inbox() { emails = new ArrayList<>(); Email email = null; for (int i = 0; i < 25; i++) { email = new Email(0, "Magda " + i, "Hello Android " + i, "This is an intro about Android"); emails.add(email); }}Copy the code

Step 2: Add Recycler View dependencies to your app/ Build. gradle file and add Recycler View to your layout

Implementation 'androidx. Recyclerview: recyclerview: 1.2.0 - beta01'Copy the code
<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerViewEmails" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>Copy the code

Step 3: Create the XML layout for the project

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/linearLayoutEmail" android:padding="@dimen/small_padding"> <TextView android:id="@+id/textViewFrom" android:layout_width="match_parent" android:layout_height="wrap_content" android:textStyle="bold" tools:text="Magda" /> <TextView android:id="@+id/textViewSubject" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/extra_small_padding"  android:textColor="@color/purple_700" tools:text="Android Fundamentals" /> <TextView android:id="@+id/textViewBody" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/extra_small_padding" Tools :text=" This is a welcome email... ." /> </LinearLayout>Copy the code

Step 4: Define the Layout Manager in the activity

private void setEmailsLayoutManager() {
      recyclerViewEmails.setLayoutManager(new LinearLayoutManager(this));
}
Copy the code

Step 5: Expand Recycler View. Separate the view holder from the class

public class EmailViewHolder extends RecyclerView.ViewHolder{ private final TextView textViewFrom, textViewSubject, textViewBody; private final LinearLayout linearLayoutEmail; public EmailViewHolder(@NonNull View itemView) { super(itemView); textViewFrom = itemView.findViewById(R.id.textViewFrom); textViewSubject = itemView.findViewById(R.id.textViewSubject); textViewBody = itemView.findViewById(R.id.textViewBody); linearLayoutEmail = itemView.findViewById(R.id.linearLayoutEmail); } public TextView getTextViewFrom() { return textViewFrom; } public TextView getTextViewSubject() { return textViewSubject; } public TextView getTextViewBody() { return textViewBody; } public LinearLayout getLinearLayoutEmail() { return linearLayoutEmail; }}Copy the code

Step 6: Expand Recycler View. Separate the adapter ** from the class

public class EmailAdapter extends RecyclerView.Adapter<EmailViewHolder> { private List<Email> emails; private Context context; public EmailAdapter(Context context, List<Email> emails) { this.emails = emails; this.context = context; } // creates the items and add them to the RecyclerView, just the layout @NonNull @Override public EmailViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(context).inflate(R.layout.email_item, parent, false); return new EmailViewHolder(itemView); } // binds (displays) the content from the list of emails for each item @Override public void onBindViewHolder(@NonNull EmailViewHolder holder, int position) { Email currentEmail = emails.get(position); holder.getTextViewFrom().setText(currentEmail.getFromName()); holder.getTextViewSubject().setText(currentEmail.getSubject()); holder.getTextViewBody().setText(currentEmail.getShortBody()); } // we tell to the Recycler View how many items to display @Override public int getItemCount() { return emails.size(); }}Copy the code

Step 7: In the on Create activity, Create a Recycler View with adapters and layout managers

private void setEmailsAdapter() { recyclerViewEmails.setAdapter(new EmailAdapter(this, emails)); } private void displayEmailsList() {// Data source -- checked Inbox (); // LayoutManager -- checked setEmailsLayoutManager(); // adapter -- checked setEmailsAdapter(); }Copy the code

Notification adapter

To not affect the rendering speed of Recycler View’s user interface elements, make sure that you are not notifying the data set changes (), setting adapters (adapters), or exchanging adapters (adapters, Bools) for small update calls. The [official recommended] solution is to use [Sorted List or] when the data source changes

public class EmailDiffCallback extends DiffUtil.Callback { private List<Email> oldList; private List<Email> newList; public EmailDiffCallback(List<Email> oldList, List<Email> newList) { this.oldList = oldList; this.newList = newList; } @Override public int getOldListSize() { return oldList.size(); } @Override public int getNewListSize() { return newList.size(); } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { // add a unique ID property on Email and expose a getId() method return oldList.get(oldItemPosition).getId() == newList.get(newItemPosition).getId(); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { Email oldEmail = oldList.get(oldItemPosition); Email newEmail = newList.get(newItemPosition); if (oldEmail.getFromName() == newEmail.getFromName() && oldEmail.getSubject() == newEmail.getSubject() && oldEmail.getShortBody() == newEmail.getShortBody()) { return true; } return false; }}Copy the code
// NOT OK
void onNewEmailsArrivedNotRecommended(List<Email> newEmails) {
    emailAdapter.setEmails(newEmails);
    emailAdapter.notifyDataSetChanged();
}

// OK
void onNewDataArrivedFastRendering(List<Email> newEmails) {
    List<Email> oldEmails = emailAdapter.getEmails();
    DiffUtil.DiffResult result = DiffUtil.calculateDiff(new EmailDiffCallback(oldEmails, newEmails));
    emailAdapter.setEmails(newEmails);
    result.dispatchUpdatesTo(emailAdapter);
}
Copy the code

Project decoration

We can use the Divider Item Decation to set separators between items

private void setItemDecorator() {
    RecyclerView.ItemDecoration itemDecoration = new
            DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
    recyclerViewEmails.addItemDecoration(itemDecoration);
}
Copy the code

Slide the refresh

Step 1: Add a new dependency to the Gradle file

Implementation 'androidx. Swiperefreshlayout: swiperefreshlayout: 1.1.0'Copy the code

Step 2: Wrap Recycler View in Swipe ReFresh Layout

<? The XML version = "1.0" encoding = "utf-8"? > <androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipeContainer" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerViewEmails" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>Copy the code

Step 3: Update the code in the adapter

// Clean all elements of the recycler
public void clear() {
    emails.clear();
    notifyDataSetChanged();
}

// Add a list of items
public void addAll(List<Email> list) {
    emails.addAll(list);
    notifyDataSetChanged();
}
Copy the code

Step 4: Set Swipe RecreLayout

private void setupSwipeToRefresh() { swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Make sure you call swipeRefreshLayout.setRefreshing(false) // once the network request has completed successfully. inbox(); }}); // Configure the refreshing colors swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); }Copy the code

You can view the full source code here.

To learn more

  • Android Vital Signs – Slow rendering

  • Use Recycler View to create dynamic lists

  • Recycler View — Google I/O2016

  • Yigit Boyar: Pro Recycler View

Feel free to leave a comment if anything is unclear or has questions. If you like it, please share!

Thank you for reading!

Pay attention to me: Twitter| | media* * * *Dev.to