How to use Recylerview using Data Binding

tech

How to use Recylerview using Data Binding

written on 2021-01-26 by SAURABH JADHAV | tech

How to use Recylerview using Data Binding

Hey Guys In previous post we have covered How to use recyclerview and use api for fetching into list,

If you haven;t read you can read it here: RecyclerView and API parsing

So in this post we will cover concept of Data Binding and How to implement recyclerview into it !

Dependency

```java implementation 'androidx.constraintlayout:constraintlayout:1.1.3' //I will use constraintlayout if u orefer Linear Layout Go ahead :)

implementation 'androidx.recyclerview:recyclerview:1.0.0' //In this post we will pass data direcly u can try using Glide etc.. //So dependancy u can add according to same ```

Enable Databinding

Build.gradle(:app)

```java android{ ....

dataBinding { enabled = true//enable this }

} ```

Add Recylerview in activity

activity_main.xml

xml <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerviewSaurabh" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="@style/TextAppearance.Body.Regular" />

Before creating itemView we will create model class ,will tell you why soon!
Model.java

```java package com.saurabh.android.app.modelname;

import android.graphics.drawable.Drawable;

public class Model {

private Drawable image; //drawable is used for accesing img from vector assets
private String t1;
private String t2;

public Model(Drawable image, String t1, String t2) {
    this.image = image;
    this.t1 = t1;
    this.t2 = t2;
}

public Drawable getImage() {
    return image;
}

public void setImage(Drawable image) {
    this.image = image;
}

public String getT1() {
    return t1;
}

public void setT1(String t1) {
    this.t1 = t1;
}

public String getT2() {
    return t2;
}

public void setT2(String t2) {
    this.t2 = t2;
}

} ```

Now We will create itemView.xml and do read the comments .
Notice:

xml <TextView android:id="@+id/Text1" android:text="@{Modelvar.t1}" //Notice this line and Model class .... " /> //This below section is important <data> <variable name="Modelvar" type="com.saurabh.android.app.modelname" /> </data>

ItemView.xml

```xml

<data>
    <variable
        name="Modelvar"
        type="com.saurabh.android.app.modelname" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout

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

    <ImageView
        android:id="@+id/Image"
        android:layout_width="@dimen/dimen_50_dp"
        android:layout_height="@dimen/dimen_50_dp"
        android:layout_marginStart="@dimen/dimen_8_dp"
        android:layout_marginLeft="@dimen/dimen_8_dp"
        android:layout_marginTop="@dimen/dimen_36_dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/Text1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dimen_36_dp"
        android:textStyle="bold"
        android:layout_marginLeft="@dimen/dimen_36_dp"
        android:layout_marginTop="@dimen/dimen_36_dp"
        android:text="@{Modelvar.t1}"
        android:textAppearance="@style/TextAppearance.Body.Header.Regular"
        app:layout_constraintStart_toEndOf="@+id/Image"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/Text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dimen_36_dp"
        android:layout_marginLeft="@dimen/dimen_36_dp"
        android:layout_marginTop="@dimen/dimen_65_dp"
        android:layout_marginEnd="@dimen/dimen_8_dp"
        android:layout_marginRight="@dimen/dimen_8_dp"
        android:text="@{Modelvar.t2}"
        android:textAppearance="@style/TextAppearance.Body.Regular"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/Image"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

```

Note:

So we can see the variables are directly use with reference of “Modelvar“ which is instance of ModelClass.

Also For image we have not passed anything as it is an Vector asset we have to pass srcCompat resource so we will pass it dynamically.

Now is Time to Create Adapter:

Adapter.java

```java public class Adapter extends RecyclerView.Adapter { private List ModelList; private Context mcontext;

public Adapter(List<Model> ModelList, Context mcontext) {
    this.ModelList = ModelList;
    this.mcontext = mcontext;
}

/* In On createViewHolder we are using ItemViewBinding where this class is automatically generated by system and we isntantiate variable binding to referr to itemView class */

@NonNull
@Override
public recyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    ItemViewBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mcontext), R.layout.itemView, parent, false);
    return new recyclerViewHolder(binding);
}

@Override
public void onBindViewHolder(@NonNull recyclerViewHolder holder, int position) {
    Model model=ModelList.get(position);

    //Image is not set directly in xml so with this we are setting it explicitely
    //using drawable
    holder.binding.Image.setImageDrawable(Model.getImage());

    /* Now the most important Step
    see we are passing whole Model 
    and see the name of setModelvar where Modelvar is variable name we defined
    in itemview.xml file so the Set__() function is created by system again!
    */

    holder.binding.setModelvar(Model);
}

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

public static class  recyclerViewHolder extends RecyclerView.ViewHolder{
    public ItemViewBinding binding;

    public recyclerViewHolder(@NonNull ItemViewBinding binding) {
        super(binding.getRoot());
        this.binding = binding;
/*Notice this View Holder class 
        we have not declare variables here also we havent used findViewBy ID
        SO we just use Binding while getRoot binds to parent layout  
        */
    }
}

} ```

So we can Notice the number of lines reduced with Binding for adapter,

Now we will make changes to Mainactivity class. we are using kotlin here.

Mainactivity.kt

```kotlin //Create Object of ModelClass we have arrayList here var Modelsobject:ArrayList = arrayListOf()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    //setting data-binding
     setUpToolBar(binding.appBarLayout)
  .....


    Modelsobject.add(Model(AppCompatResources.getDrawable(this,R.drawable.img1),"Life is beauty","Dance like a wind"))
    //adding data to arraylist
    //appcompatresources help to use drawables
     Modelsobject.add(Model(AppCompatResources.getDrawable(this,R.drawable.img2),"Life is beauty again","Dance like a wind again"))

    setupRecyclerView();
    //we will define this now

}

/* Out of Oncreate we will define our recyclerview */ private fun setupRecyclerView() { val layoutManager=LinearLayoutManager(this) //creating instance of Linearlayout

    binding.recyclerview.layoutManager=layoutManager
 //binding it to recyclerview
    //It is as simple as this !
    binding.recyclerview.adapter=Adapter(Modelsobject,this)
 //Done hurray!!!
}

```

So yes guys we have successfully Implemented it !

Hope you enjoyed it !

In next tutorials we will see more about kotlin !

So stay tuned!

Thank you :)