Category

Data Binding

Category

Android improved ListView in shape of RecyclerView. RecyclerView provides the advanced feature like horizontal, vertical and grid. Use of  CardView in RecyclerView provides effective representation of UI.

In this tutorial, you will learn, how to show the list of posts using RecyclerView and CardView. I will also tell how to use the adapter for RecyclerView.

This is the tag of RecyclerView in Android XML.

   <android.support.v7.widget.RecyclerView
            android:id="@+id/listing"
            android:layout_margin="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

the tag of CardView in Android XML

   <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.CardView>

1- Create a new project

I am creating a new project, before creating a new project, please check your latest Android Studio and Gradle version.

1-  In Android Studio, go to File ⇒ New Project and fill all the details required to create a new project.

2- Select the available template, I will suggest BasicActivity template.

3- In your Android Gradle, add RecyclerView and CardView dependencies.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "becody.com.recyclerviewexample"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding{
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:cardview-v7:27.1.1'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

4- Create a layout XML named adapter_post.xml with the below code. This layout file renders a single row in recycler view by displaying the single post.

<?xml version="1.0" encoding="utf-8"?>
<layout 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.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@android:color/white"
        app:cardCornerRadius="3dp"
        app:cardElevation="5dp"
        app:cardUseCompatPadding="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp">

            <TextView
                android:id="@+id/txt_post"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="5dp"
                android:text="Hi everyone, I am owner of becody.com, if you need any help kindly leave comments" />
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</layout>

5-  Before writing an adapter class, I am writing a modal class named Post.java.

package becody.com.recyclerviewexample.modals;

/**
 * Created by ranaaamersohail on 7/4/18.
 */

public class Post {
    private String post;

    public String getPost() {
        return post;
    }

    public void setPost(String post) {
        this.post = post;
    }
}

6- Now create a class named AdapterPost.java and add the below code. Now extend RecyclerView.Adapter<RecyclerView.ViewHolder> in PostAdapter.java class. RecyclerView.An adapter provides three main method which is mandatory in the adapter class.

  •  onBindViewHolder
  • getItemCount
  • onCreateViewHolder
      

in the getItemCount method, you will return the total size of your list data. In createViewHolder method, you will return your adapter XML.

LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_post, parent, false);

7- Create your view holder class which will hold your components objects.

  private class CellViewHolder extends RecyclerView.ViewHolder {
        private TextView txt_post;

        public CellViewHolder(View itemView) {
            super(itemView);
            txt_post = (TextView) itemView.findViewById(R.id.txt_post);
        }
    }

below is the full code of AdapterPost.java class

package becody.com.recyclerviewexample.adapters;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

import becody.com.recyclerviewexample.R;
import becody.com.recyclerviewexample.modals.Post;

/**
 * Created by ranaaamersohail on 7/4/18.
 */

public class AdapterPost extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<Post> dataList;

    public AdapterPost(List<Post> dataList) {
        this.dataList = dataList;
    }

    private class CellViewHolder extends RecyclerView.ViewHolder {
        private TextView txt_post;

        public CellViewHolder(View itemView) {
            super(itemView);
            txt_post = (TextView) itemView.findViewById(R.id.txt_post);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        switch (viewType) {
            default: {
                View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_post, parent, false);
                return new CellViewHolder(v1);
            }
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            default: {
                CellViewHolder cellViewHolder = (CellViewHolder) holder;
                Post data = dataList.get(position);
                cellViewHolder.txt_post.setText(data.getPost());
                break;
            }
        }
    }

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

In your main_activity class. Put tag of RecyclerView like that

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
  >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/listing"
            android:layout_margin="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>

</layout>

You can see that my parent root tag is a layout, I am working with data binding, if you don’t know about data binding, kindly read my https://becody.com/category/android/medium/data-binding/.

full code of MainActivity.java is

package becody.com.recyclerviewexample;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import becody.com.recyclerviewexample.adapters.AdapterPost;
import becody.com.recyclerviewexample.databinding.ActivityMainBinding;
import becody.com.recyclerviewexample.modals.Post;


public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private List<Post> dataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        dataList = new ArrayList<>();
        initVal();
    }

    private void initVal() {
        String[] postArrVal = getResources().getStringArray(R.array.str_arr_posts);
        for (String val : postArrVal) {
            Post data = new Post();
            data.setPost(val);
            dataList.add(data);
        }
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.listing.setLayoutManager(manager);
        AdapterPost adapterData = new AdapterPost(dataList);
        binding.listing.setAdapter(adapterData);
    }
}

In Strings.xml I have an array of the post which I am displaying in RecyclerView.

<resources>
    <string name="app_name">recyclerviewexample</string>
    <string name="action_settings">Settings</string>
    <string-array name="str_arr_posts">
        <item>Hello Everyone So I recently published a blog called becody.com </item>
        <item>On the Followers page at (My Sites) Stats, the heading WordPress.com  </item>
        <item>Thank you for the reply. I have browsed into it and finally see the Email Followers  </item>
        <item>No. I dont have an explanation for that discrepancy. I ll tag the topic for staff attention.</item>
        <item>I had difficulties with finding this option where you can check out your subscribers but that topic helped me </item>
        <item>So I recently published a blog called becody.com and so far I have 1 follower and 33 subscribers via email</item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
        <item>but when I browsed email followers tab, there no one listed there. Strange </item>
    </string-array>
</resources>

 

Download Source Code