View Recycling in Android with ListView - GeeksforGeeks

18 Feb, 2021
Memory management is a crucial aspect of app development. Since mobile devices have very limited memory, it is necessary to use it carefully in our applications. One of the best practices involved in doing so is “view recycling“.
This article is about view recycling in Android and then a simple app is created which implements the practice of view recycling using ListView and ArrayAdapter in conjunction.
Need for View Recycling in AndroidIt is a practice to use as little memory as possible by recycling unused views to display new content instead of creating new views for the same. Suppose, we are scrolling down through a list of one thousand words. If we create a TextView for each word, we would need one thousand TextViews for this. This would waste a lot of memory since our device’s screen displays only 7-8 TextViews at a time and we need to scroll down if we want to see the rest of them.
When we scroll down, the TextViews which are at the top are not visible anymore. So, an inference can be taken that the top TextViews are not used by the user when they scroll down the ListView. Hence, unused TextViews are recycled and are used at the bottom when the user scrolls down. This way, instead of having one thousand TextViews, our task can be achieved with a few of them only.
Example for View Recycling in AndroidOne of the most common example is our mobile’s phone-book. We can have many contacts on our phone but instead of creating a new TextViews for each contact, our phone just recycles the unused scrolled up/down views and fills them with the new contact information and displays it again when the user scrolls up/down.
Implementation of View Recycling using ArrayAdapter and Listview
ArrayAdapter is a Java public class which extends from BaseAdapter class. An ArrayAdapter object makes the data (which is to be displayed) adapt to an array. Basically adapter is a bridge between UI component and data that helps to fill data in the UI component.
ListView is a Java public class which extends from AbsListView. ListView is a view which groups several items and displays them in a vertical list. This list is also automatically made scrollable if the amount of data supplied cannot be accommodated on the screen.
ArrayAdapter and ListView are required for view recycling. ListView asks for views from ArrayAdpapter by sending it a request and a specified position. ArrayAdpapter then returns the view at the specified position as the ListView keeps on asking for it until the device’s screen is filled. Now, when the user scrolls down, ListView gives ArrayAdpapter the top views which aren’t displayed on the device’s screen anymore. The ArrayAdpapter then erases the previous data of that ScrapView and sets new data and returns it to the ListView instead of creating a new view!
Below is a simple app to demonstrate this practice of memory management.
Step 1: Add the below code in activity_main.xml file which would just contain a ListView and a TextView.activity_main.xmlactivity_main.xml<LinearLayout    android:layout_height="match_parent"    android:layout_width="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:background="#66bb6a"    android:padding="8dp">      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stuff you can learn at GeeksforGeeks:"        android:background="#a5d6a7"        android:textSize="22sp"        android:fontFamily="sans-serif-condensed-light"        android:textColor="#fafafa"/>    <ListView        android:id="@+id/list"        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>Output:
activity_main.xml
<LinearLayout    android:layout_height="match_parent"    android:layout_width="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:background="#66bb6a"    android:padding="8dp">      <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Stuff you can learn at GeeksforGeeks:"        android:background="#a5d6a7"        android:textSize="22sp"        android:fontFamily="sans-serif-condensed-light"        android:textColor="#fafafa"/>    <ListView        android:id="@+id/list"        android:orientation="vertical"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>
Output:
Step 2: In the below code, when we initialize the ArrayAdapter, we pass a layout called android.R.layout.simple_list_item_1 along with our ArrayList and Context. The android.R.layout.simple_list_item_1 is a inbuilt layout that describes the design in which a single list item will be shown. It conventionally consists of just a single TextViewOnce the ListView and ArrayAdapter are initialized, set the ArrayAdapter on the ListView using the setAdapter() method.MainActivity.javaMainActivity.javapackage com.example.gfgrecycleview;  import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;  import java.util.ArrayList;  public class MainActivity    extends AppCompatActivity {      public static final        String LOG_TAG        = MainActivity.class              .getName();      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // Create a list of study fields.        ArrayList<String> stuff = new ArrayList<>();        stuff.add("Data Structures");        stuff.add("Algorithms");        stuff.add("Competitive Programming");        stuff.add("Interview Questions");        stuff.add("Python");        stuff.add("Java");        stuff.add("Designing");        stuff.add("Coding");        stuff.add("Developing");        stuff.add("Project Ideas");        stuff.add("C++");        stuff.add("Basically Everything!");          // Find a reference to the        //{@link ListView} in the layout        ListView itemListView            = (ListView)findViewById(R.id.list);          // Create a new {@link ArrayAdapter}        // of study fields        ArrayAdapter<String> adapter            = new ArrayAdapter<String>(                this,                android.R.layout.simple_list_item_1,                stuff);          // Set the adapter        // on the {@link ListView}        // so the list can be populated        /// in the user interface        itemListView.setAdapter(adapter);    }}Output:Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200608114433/Android-Emulator-Nexus_4_API_23_5556-2020-06-08-11-10-27_Trim.mp400:0000:0000:12Use Up/Down Arrow keys to increase or decrease volume.Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes
arrow_drop_upSave
MainActivity.java
package com.example.gfgrecycleview;  import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;  import java.util.ArrayList;  public class MainActivity    extends AppCompatActivity {      public static final        String LOG_TAG        = MainActivity.class              .getName();      @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // Create a list of study fields.        ArrayList<String> stuff = new ArrayList<>();        stuff.add("Data Structures");        stuff.add("Algorithms");        stuff.add("Competitive Programming");        stuff.add("Interview Questions");        stuff.add("Python");        stuff.add("Java");        stuff.add("Designing");        stuff.add("Coding");        stuff.add("Developing");        stuff.add("Project Ideas");        stuff.add("C++");        stuff.add("Basically Everything!");          // Find a reference to the        //{@link ListView} in the layout        ListView itemListView            = (ListView)findViewById(R.id.list);          // Create a new {@link ArrayAdapter}        // of study fields        ArrayAdapter<String> adapter            = new ArrayAdapter<String>(                this,                android.R.layout.simple_list_item_1,                stuff);          // Set the adapter        // on the {@link ListView}        // so the list can be populated        /// in the user interface        itemListView.setAdapter(adapter);    }}
Output:
android
Android-View
Android
Java
Write From Home
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples