Friday, 25 August 2017

RecyclerView Example with custom adapter in Android




What is RecyclerView in android?

RecyclerView is more advance version of ListView. When you want to change your dataset at run time, RecylerView is very much useful to use. 


Here I am going to give an example of RecyclerView with Custom Adapter.
Step1
First Create a project using Android-Studio, with name "RecylerViewSample" with package name "recyle.sample"
Keep your activity name:  MainActivity.java and layout name activity_main.xml

Step2:
Inside activity_main.xml add recylerview. Full code bellow:

activity_main.xml

<?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.support.v7.widget.RecyclerView        
                     android:id="@+id/rv_fruit_list"        
                     android:layout_width="match_parent"        
                     android:layout_height="match_parent"
                     android:scrollbars="none"/>

</LinearLayout>

Here I am giving recyler id name rv_fruit_list.

Step3:
Now create model class name Fruit.java. Here I am addinfg three variables fruitName, fruitDetails and fruitPrice. Also creating constructor and getter-setter method.  I am creating this model class because of custom adapter. This model class will contain fruit data and it will show in recyler-view. Full Code is bellow:

Fruit.java:

package recyle.sample;



public class Fruit {


    private String fruitName;
    private String fruitDetails;
    private String fruitPrice;


    public Fruit(String fruitName, String fruitDetails, String fruitPrice) {
        this.fruitName = fruitName;
        this.fruitDetails = fruitDetails;
        this.fruitPrice = fruitPrice;
    }

    public String getFruitName() {
        return fruitName;
    }

    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }

    public String getFruitDetails() {
        return fruitDetails;
    }

    public void setFruitDetails(String fruitDetails) {
        this.fruitDetails = fruitDetails;
    }

    public String getFruitPrice() {
        return fruitPrice;
    }

    public void setFruitPrice(String fruitPrice) {
        this.fruitPrice = fruitPrice;
    }
}

Step4: 
Add recyler view inside build.gradle file:
compile 'com.android.support:recyclerview-v7:25.0.1'
Create a xml file name fruit_recyle_adapter.xml , which will be used inside adapter file. Code bellow:

fruit_recyle_adapter.xml

<?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_gravity="center"    
              android:orientation="vertical">


              <TextView        
                  android:id="@+id/txt_fruit_name"        
                  android:layout_width="wrap_content"        
                  android:layout_height="wrap_content"        
                  android:ellipsize="end"        
                  android:gravity="left"        
                  android:maxLines="2"        
                  android:padding="6sp"        
                  android:text="Name"        
                  android:textColor="#000000" />

              <TextView        
                  android:id="@+id/txt_fruit_details"        
                  android:layout_width="wrap_content"        
                  android:layout_height="wrap_content"        
                  android:ellipsize="end"        
                  android:gravity="left"        
                  android:maxLines="2"        
                  android:padding="6sp"        
                  android:text="Details"        
                  android:textColor="#000000" />


    <LinearLayout        
       android:layout_width="match_parent"        
       android:layout_height="wrap_content"        
       android:orientation="horizontal">
           <TextView            
               android:layout_width="wrap_content"           
               android:layout_height="wrap_content"            
               android:textSize="16sp"            
               android:padding="6sp"            
               android:text="@string/rs"            
               android:textColor="@color/colorAccent"/>
           <TextView            
               android:id="@+id/tv_fruit_price"            
               android:layout_width="match_parent"            
               android:layout_height="wrap_content"            
               android:layout_gravity="left"            
               android:padding="6sp"            
               android:text="3000"            
               android:textColor="@color/colorAccent"            
               android:textSize="16sp" />
    </LinearLayout>


</LinearLayout>

Here @string/rs value is <string name="rs">\u20B9</string> .

Now create one more class FruitRecylerAdapter.java . Inside this class create Holder class name FruitHolder, codes bellow:

public class FruitHolder extends RecyclerView.ViewHolder{

    public TextView fruitName,fruitDetails,fruitPrice;

    public FruitHolder(View itemView) {
        super(itemView);

        fruitName = (TextView)itemView.findViewById(R.id.txt_fruit_name);
        fruitDetails = (TextView)itemView.findViewById(R.id.txt_fruit_details);
        fruitPrice = (TextView)itemView.findViewById(R.id.tv_fruit_price);
    }
}
Full Code For FruitRecylerAdapter.java bellow:


package recyle.sample;

import android.content.Context;
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;


public class FruitRecylerAdapter extends RecyclerView.Adapter<FruitRecylerAdapter.FruitHolder>{


    List<Fruit> listFruit;
    Context mContext;


    public FruitRecylerAdapter(Context con,List<Fruit> fList){
        mContext = con;
        listFruit = fList;
    }

    @Override    public FruitHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).
                        inflate(R.layout.fruit_recyle_adapter, parent, false);
        return new FruitHolder(itemView);
    }

    @Override    public void onBindViewHolder(FruitHolder holder, int position) {

        Fruit f = listFruit.get(position);

        holder.fruitName.setText(f.getFruitName());
        holder.fruitDetails.setText(f.getFruitDetails());
        holder.fruitPrice.setText(f.getFruitPrice());
    }

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

    public class FruitHolder extends RecyclerView.ViewHolder{

        public TextView fruitName,fruitDetails,fruitPrice;

        public FruitHolder(View itemView) {
            super(itemView);

            fruitName = (TextView)itemView.findViewById(R.id.txt_fruit_name);
            fruitDetails = (TextView)itemView.findViewById(R.id.txt_fruit_details);
            fruitPrice = (TextView)itemView.findViewById(R.id.tv_fruit_price);
        }
    }

}


Step5:

Now we will go to MainActivity.java
Firstly we need to add static data inside list which will show inside recyle-view.  Now we will create a method, name setStaticDataForFruit() which will hold static data.

private void setStaticDataForFruit(){

    Fruit f1 = new Fruit("Apple","Vitamin A,B1,B2,B6,C,Folate (folic acid)","300");
    Fruit f2 = new Fruit("Banana","Vitamin A,B1,B2,B6","10");
    Fruit f3 = new Fruit("Orange","Vitamin A,B1,B2,B6,Folate (folic acid)","10");

    listFruit.add(f1);
    listFruit.add(f2);
    listFruit.add(f3);

}

After creating static method, now we need to set adapter. Code Bellow:

private void setRecyleAdapter() {
    LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), 
                                            LinearLayoutManager.VERTICAL, false);
    rvFruitList.setLayoutManager(layoutManager);
    fruitAdapter = new FruitRecylerAdapter(MainActivity.this, listFruit);
    rvFruitList.setAdapter(fruitAdapter);

    //Updating recyler Adapter    fruitAdapter.notifyDataSetChanged();

Now Full Code Bellow:

MainActivity.java

package recyle.sample;

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

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

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.rv_fruit_list)
    RecyclerView rvFruitList;

    FruitRecylerAdapter fruitAdapter;
    List<Fruit> listFruit = new ArrayList<>();

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //Setting static Data        
        setStaticDataForFruit();

        //System.out.println("List::"+listFruit);

        //Setting Adapter        
        setRecyleAdapter();

    }


    

    private void setRecyleAdapter() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(       
        getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        rvFruitList.setLayoutManager(layoutManager);
        fruitAdapter = new FruitRecylerAdapter(MainActivity.this, listFruit);
        rvFruitList.setAdapter(fruitAdapter);

        //Updating recyler Adapter        
          fruitAdapter.notifyDataSetChanged();

    }

    private void setStaticDataForFruit(){

        Fruit f1 = new Fruit("Apple","Vitamin A,B1,B2,B6,C,Folate (folic acid)","300");
        Fruit f2 = new Fruit("Banana","Vitamin A,B1,B2,B6","10");
        Fruit f3 = new Fruit("Orange","Vitamin A,B1,B2,B6,Folate (folic acid)","10");

        listFruit.add(f1);
        listFruit.add(f2);
        listFruit.add(f3);

    }

}

Also providing you build.gradle file:

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25    
    buildToolsVersion "25.0.2"    
    defaultConfig {
        applicationId "recyle.sample"        
        minSdkVersion 15        
        targetSdkVersion 25        
        versionCode 1        
        versionName "1.0"        
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }
    buildTypes {
        release {
            minifyEnabled false            
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'        
}
    }
}

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'    
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:recyclerview-v7:25.0.1'    
    compile 'com.jakewharton:butterknife:7.0.1'
}


Screen-Shots:













No comments:

Post a Comment