Categories
Studio

RecyclerView – The Easiest Approach (Weekly Series – Day1)

Weekly Series (Guides)

This is the first guide in this series. What a beautiful start to the development (Studio) part of this blog. Though RecyclerView tutorials are already there on the web (including the official one) and I am going to share the easy to implement approach with you.

I have learned from my few Android apps that the key widget I need in most of the apps to show the data is RecyclerView. Hence, I have good experience of adding this to my projects. There you go.

How to Add RecyclerView to your Android Project.

First, Add the RecyclerView library to your Gradle file.

  1. Go to Gradle Scripts > build.gradle (module: app)
    [Refer screenshot]
    Android Studio Gradle file location
  2. Now in dependencies, add the following line:
    implementation 'com.android.support:recyclerview-v7:27.1.1'
  3. The bold text is the version number of this library and it changes based on your target SDK.

Now, Add RecyclerView in your activity layout file (XML).

(The code for a basic RecyclerView)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.a101android.practice.RecyclerView.RecyclerViewMain">

<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recyclerViewMain"
android:scrollbars="vertical"
android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Now in your Activity (MainActivity, in our case), You need to add RecyclerView, its LayoutManager and Adapter.

Initialise RecyclerView with the following line.

RecyclerView recyclerView = findViewById(R.id.recyclerViewMain);

Initialise RecyclerView LayoutManager with LinearLayoutManager. Note: You can also use GridLayoutManager or StaggeredGridLayoutManager depending upon the need of your app’s UI.

LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);

Now create a private class extending RecyclerView.Adapter. Start by writing the following line, do not copy the full code from the guides you have been learning ever since.

public class NewAdapter extends RecyclerView.Adapter<NewAdapter.ViewHolder>

This class will help us initialize RecyclerView’s adapter. Upon writing this line, you’ll see red curly underline. Right-click on that line or press option+enter(Mac) to implement the methods. This will now have more red curly underlines until you right click on each red line and set the code. ViewHolder is a custom class and must match with the declared type.

The type of the ViewHolder must match the type declared in the Adapter class signature. Typically, it would set the view by inflating an XML layout file. Because the view holder is not yet assigned to any particular data, the method does not actually set the view’s contents.

The code for NewAdapter now looks like this:

public class NewAdapter extends RecyclerView.Adapter<NewAdapter.ViewHolder>
{

    @NonNull
    @Override
    public NewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return null;
    }

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

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }
    }
}

You’ll need two variables now. Context and ArrayList<String> (or String[]). The second variable’s type is completely based on the app’s requirements. For the illustration purpose, I will use ArrayList<String>.

You’ll now create an XML layout file for a single item of recyclerView. It can be as simple as having just a TextView or as complex as having multiple UI widgets. For the practice, let’s create a simple XML layout file. The complete code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:id="@+id/textViewRecycler_Main"
        android:layout_height="wrap_content" />

</LinearLayout>

Now back to NewAdapter class. Initialise Context, ArrayList<String> and make NewAdapter’s constructor.

  1. Now set getItemCount(), Replace 0 to dataset.size().
  2. In ViewHolder class, initialize the TextView (complete code is available at the bottom).
  3. In OnCreateViewHolder, we will initialize our single_layout file.
  4. In onBindViewHolder, we will set the single item data (setText for TextView).

The final NewAdapter will look like this after all these changes:

public class NewAdapter extends RecyclerView.Adapter<NewAdapter.ViewHolder>
{
    private ArrayList<String> dataset;
    private Context context;

    public NewAdapter(ArrayList<String> dataset, Context context) {
        this.dataset = dataset;
        this.context = context;
    }

    @NonNull
    @Override
    public NewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.recycler_main_single, parent, false);
        return new ViewHolder(linearLayout);
    }

    @Override
    public void onBindViewHolder(@NonNull NewAdapter.ViewHolder holder, int position) {
        holder.textView.setText(dataset.get(position));
    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.recyclerViewMain);
        }
    }
}

Now let’s have some fake data to put the app into action. Initialize ArrayList<String> with some fake data and set the adapter. Our onCreate function should look like this now:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recycler_view_main);

    // init and set layout manager
    RecyclerView recyclerView = findViewById(R.id.recyclerViewMain);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);


    // data.
    ArrayList<String> namesOfViews = new ArrayList<>();
    namesOfViews.add(0, "Recycler View 1 (Official Demo)");
    namesOfViews.add(1, "Recycler View 2");
    namesOfViews.add(2, "Recycler View 3");
    namesOfViews.add(3, "Recycler View 4");
    namesOfViews.add(4, "Load More - RV");

    // set adapter
    RecyclerView.Adapter adapter = new NewAdapter(namesOfViews);
    recyclerView.setAdapter(adapter);

}

Now run the code and see the app in action. In near future, I’ll write a guide on some complex RecyclerView codes with custom data set to ArrayList. But as of now for a beginner, this should help you kick-start your journey. Play with this code and practice with your own implementations.

Complete Code on GITHUB.

If you like this guide then write a comment mentioning that you liked it. If you think something can be improved then let me know in the comments section. This is my first Android guide.

Leave a Reply

Your email address will not be published. Required fields are marked *