Android Recycler View Tutorial

sapan

In Android there is the need when you need to display a list of data or simply data that get generated at run-time. Rather than creating your own layout inflator. Android provide Recycler View, there is also a listview which was provided to show data.

After after many experiments with Recycler View here is the tutorial for it. Hope it will be use full to someone.I assume if you are reading this then you know how to add activity in the android studio.

I have divided the article into several parts. Here is the First part.

Part 2 : http://www.androidlearner.com/2017/11/android-recycler-view-tutorial-part-2.html

Here is the video of it :




# First Create an Android Project.

#Compiling the required library

Open your build.gradle file for (module:app) level
add line compile 'com.android.support:recyclerview-v7:25.3.1'  in the dependencies section.
this will download recycler view dependencies in the project.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    //Recycler view library -- its version should be similar as appcompact.
    // It can also be used as
    //compile 'com.android.support:recyclerview-v7:25.+'
    compile 'com.android.support:recyclerview-v7:25.3.1'

    testCompile 'junit:junit:4.12'
}


# Add the Recycler view to the layout.

Open your layout file and add the View.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="skd.app.androidfeatures.sRecylerView.RecylerActivity">

    <!-- Recycler view -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

# Initializing the Recycler View in your activity class.


Recycler view requires 3 components to set it up.

  • The Recycler view widget from the layout.
  • The Data Adapter for the view , This contain the data which need to be shown
  • The LayoutManager , it defines how data is shown in the Layout.
Now open your Activity Class which corresponds to the layout which contain the recycler view.
and set up your Recycler View.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import skd.app.androidfeatures.R;

public class RecylerActivity extends AppCompatActivity {


    //Below are the componets which are required by the Recycler view
    RecyclerView recyclerView; //this will hold the recycler view from the layout
    RecyclerView.Adapter   mAdapter; //this will hold the adapter for the recycler view
    RecyclerView.LayoutManager mLayoutmanager; //holds the layout manager

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recyler); //layout which contain the recycler view

        //Find the Recycler view
        recyclerView = (RecyclerView)findViewById(R.id.my_recycler_view); //got the recycler view from the layout

        //set the layout manager for the recycler view
        //standard layout managers( LinearLayoutManager or GridLayoutManager) can be used, or implement your own.
        //Layout Manager tells how the item are shown in your Recycler View
        mLayoutmanager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mLayoutmanager);

        //set the data adapter
        //Adapter contain the Data Which need to be shown in the view
        mAdapter = new RvDataAdpt();
        recyclerView.setAdapter(mAdapter);
    }
}


#Recycler View Item


Now we need to create and recycler item , i.e the layout which can be shown by the recycler view.
Add layout recycler_item.xml




1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?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="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hii "
        android:textSize="30sp" />
</LinearLayout>


# The Data Adapter

The data Adapter is the component which feeds to the recycler view. In the post I will describe how to set up the basic adapter class to able to show the view. listening events from the view will be decribed in a later post :).

As per Android doc your adapter class must extent RecyclerView.Adapter class from the support library.


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import skd.app.androidfeatures.R;

/**
 * THis class will be the data adapter for the recycler view
 * This class must exxtend the Recycler view adapter.
 */
public class RvDataAdpt extends RecyclerView.Adapter {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0; 
    }
}

These methods are need overridden by the base class.

onCreateViewHolder : This method used to construct the view holder and set the view it uses
 to display its contents. Typically, it would set the view by inflating an XML layout file.

onBindViewHolder : Called by RecyclerView to display the data at the specified position. This method should update the contents of the itemView to reflect the item at the given position.

getItemCount : Returns the total number of items in the data set held by the adapter.

For more info visit Recycler Adapter

At this point if you run the application. Recycler view will be visible however with no item.
Now lets try to display our item layout in the recycler.

To display the item in the recycler view we need to inflate our item in the onCreateViewHolder  method however. However this method return data of RecyclerView.ViewHolder , so we first need to convert or return our view as ViewHolder type. By creating instance of ViewHolder Class.

To set the count of the item displayed. getItemCount should return value greater than 0.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import skd.app.androidfeatures.R;

/**
 * THis class will be the data adapter for the recycler view
 * This class must exxtend the Recycler view adapter.
 */
public class RvDataAdpt extends RecyclerView.Adapter {
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        //lets populate our recyler view with the item created;
        //get the view from the layout inflator
        //  third parameter is set to false to prevent viewgroup to attach to root
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item,parent,false);

        // as this method need to return the viewHolder type
        // need to convert our view to the view holder
        RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view) {
            @Override
            public String toString() {
                return super.toString();
            }
        };
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
  //this defined how many items need to be displayed
        return 3000; // to display the 3000 items
    }
}


Now After compiling and running the application you will get something like this.

In the next post I will describe how to use Recycler view with proper items ,with data model and listing to the events of the items.

Source Code : - https://github.com/sapandang/AndroidFeatures

Post a Comment

40Comments
  1. Nex Gen Media Server is best known as a multi-purpose media streaming server to deliver live and stored video to a variety of devices. The same media server can be embedded into a mobile application to facilitate real time video communication. Here we will use the NGMS API picsay pro mod apk to facilitate building a video chat client for Android devices of picsay pro mod apkusing the Android Software Developer Kit (SDK) and Google Android Native Developer Kit (NDK).

    ReplyDelete
  2. Android phone application is the best software that can be used in mobile devices with middle ware, operating system and key applications. Android phone application of dragon mania legends hacked apk has been a hot pick by all gizmo freaks because of the unmatched features it offers. It is both a professional and entertainment phone and satisfies all types of customers to their maximum.

    ReplyDelete
  3. Download latest and updated version of War Robots MOD Apk for android.

    ReplyDelete
  4. Androidlearner.com always gives a new satisfactory result that was we aspecting. Keep it up, guys. I tried this style on wcc3 where i learn more.

    ReplyDelete
  5. there are 900,000 Android apps developed, with more than 30 billion downloads by its users. This has been made possible by its adaptation of the open-source philosophy, which lets developers utilize the back wars mod apk entire system stack to create applications.

    ReplyDelete
  6. Thanks for sharing this post click here to know more.

    ReplyDelete
  7. Hey this article is best and from this we really learned about the android recycler view mod apk in one click.

    ReplyDelete
  8. Great post but you can check Alight motion pc latest version and install in your pc and get free millions of animation effects and many more things

    ReplyDelete
  9. Astracraft Mod APK is a battlebots, drones, robots, mechs game. download Astracraft Mod APK Unlimited Star Coins, Unlimited Pixel Sunglasses Astracraft Mod APK Unlimited Star

    ReplyDelete
  10. After the on line casino verifies your id, the final step earlier than taking part in} is to add funds to your account. All our beneficial Ohio playing apps have a solid track document of 소울카지노 a secure and dependable playing expertise. With the variety of on-line casinos available within the country, there may be} broad variety|all kinds} of games to choose from|to select from}.

    ReplyDelete
  11. If you are a pc user and want to use Alight motion pc without water mark then Download Latest version of Alight motion pc here

    ReplyDelete
  12. I really enjoyed your post. It was excellent. This post is a treasure trove of information Also try out Minecraft Mod.

    ReplyDelete
  13. Thank you for your post. Also check my post of alight motion mod apk.

    ReplyDelete
  14. Thank you for the suggestion. I need it since I have to download outside apps, such MBWhatsApp APK. It will therefore be helpful to me.

    ReplyDelete

  15. I thoroughly enjoyed your post; it was outstanding. This article is a wealth of information. Additionally, give Visit instabioforgirl.com a try.

    ReplyDelete
  16. Thanks for amazing content, I must refer to Alight motion and the results I am getting from this app is amazing

    ReplyDelete
  17. Unlock powerful video editing features with the Alight Motion Pro Mod APK Elevate your creativity with premium tools and effects for free. Download now for an enhanced editing experience!

    ReplyDelete
  18. If you want to download capcut and alight motion but you don't know which video editor is best for your device this article will help you understand which video editor is best for your device.
    Here is the link

    ReplyDelete
  19. Great Information I have read all these and took a SC of it and then edit on alight motion fonts, for further clearance.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Earthquake Safety Information In regions prone to seismic activity, understanding earthquake safety is paramount. Prepare your household with essential measures to mitigate risks and ensure resilience. Prioritize structural assessments to reinforce buildings and secure heavy furniture to prevent hazards during tremors. Develop an emergency plan, including designated meeting points and communication protocols. Assemble a disaster kit with essentials such as water, non-perishable food, first aid supplies, and flashlights. Familiarize yourself with evacuation routes and practice drills regularly. Stay informed through reliable sources for updates and guidance. By adopting proactive measures, you empower yourself and your community to navigate earthquakes with confidence and safety.

    ReplyDelete
  22. Vivacut Mod APK offers a dynamic video editing experience. With its intuitive interface and powerful features, users can effortlessly create stunning videos on their mobile devices. From trimming and merging clips to adding effects and music, Vivacut Mod APK unlocks endless possibilities for crafting captivating visual stories.

    ReplyDelete
  23. good post this one i really enjoy free

    ReplyDelete
  24. i use this code on animal site to create app for world animals foundation

    ReplyDelete
  25. In the realm of Android development, implementing RecyclerView mirrors the structured approach of navigating parking challenges in Car Parking Multiplayer. Both streamline processes, optimize performance, and enhance user interaction, contributing to a seamless and enjoyable experience.

    ReplyDelete
  26. Open your account on Spotify Premium
    for Students; Navigate to your account page and choose Account overview > Activate Hulu; Fill out the necessary information and...

    ReplyDelete
  27. In the world of crypto presales,
    keeping track of ever-changing data is crucial. Just like Android developers use RecyclerView to efficiently handle dynamic lists, you can leverage similar principles to manage and visualize real-time crypto presale data. This tutorial on RecyclerView can offer valuable insights into structuring and displaying your presale data efficiently. Dive into this guide to enhance your data management skills and stay on top of the latest opportunities in the crypto space. I hope you find this series as useful for your investment strategies as I did for my development projects!

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. i use this code on video editing site to create app like alight motion mod apk 2024

    ReplyDelete
  30. this information proved to be very helpful for me...i must refer to this app.. also must try wsop free chips dailywsop

    ReplyDelete
    Replies
    1. An Android RecyclerView tutorial guides developers on how to efficiently display large datasets using a flexible layout manager and view holder pattern. It covers setup, adapters, and how to bind data for smooth scrolling and dynamic content updates.
      If you want to get up to date with the guides and tutorials, you can participate in Fmwhatsapp apk channels. The fmwhatsapp apk is one of the best alternative to original whatsapp. It provides many extra features that normal whatsapp cannot provide.

      Delete
  31. Starbucks Partner Hours allow employees to efficiently manage their schedules. Partners can view their shifts, request time off, and track their work hours easily.

    ReplyDelete
  32. Log in to your Spotify Premium
    for Students account, go to your account page, select "Account Overview," then click "Activate Hulu." Complete the required details.

    ReplyDelete
  33. With realistic graphics, lifelike physics, and dynamic controls, the gameplay feels incredibly immersive, whether you're navigating tight parking spaces or speeding through open roads. Missions, free roam, and social features like in-game chat add to the excitement, making the game highly engaging. Whether you're a casual gamer or a driving enthusiast, Car parking multiplayer mod apk (unlimited money and gold) offers endless fun, creativity, and opportunities to showcase your skills in a virtual world. https://carparkingmultiplayer2modapk.com/

    ReplyDelete
  34. If you're looking for reliable roofing services in Greenville, NC, check out roofers greenville nc. They specialize in roof repairs, installations, and maintenance. Known for their professional and quality work, they are a trusted choice for roofing needs. Visit their website to learn more about their services and how they can help with your roofing projects.

    ReplyDelete
  35. The Spike stands out as one of the best volleyball games available, combining realistic mechanics with a captivating story and competitive gameplay. Whether you’re a volleyball enthusiast or just looking for an engaging sports game, The Spike is well worth your time.

    ReplyDelete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !