Android Data binding

Now android supporting the Data binding library, that allows you to bind UI components in your layouts (xml) to data sources in your application using a declarative format and avoid programmatically.

Android Data binding

Android Data binding

Please download sample project from here.  AndroidDataBinding 

Benifits:

  1. Data binding can lead to faster development times
  2. Faster execution times (more then findviewbyid)
  3. Stronger readability (More readable and maintained code).
  4. Remove boilerplate code

Drawback :

  1. Auto generated class (it's true it will increase the app size)
  2. Hard to debug - depends, like readability, of what you are used to.

 

To enable data binding :

android { 

................

dataBinding{
    enabled = true
}

}

OR

android { 

....................................

dataBinding.enabled true
}

 

 

----------------------------------------------------------------

Creating a sample project in android studio

1. Create a sample project from android studio. to create a sample project please go to below steps:

File  -> New -> New Project --> A popup will come then select a empty activity.

2. Open project app -> res -> change resource values file like strings, color, dimens.

colors.xml  :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>

styles.xml : 

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

string.xml :

<resources>
    <string name="app_name">AndroidDataBinding</string>
</resources>

3. Now enable databinding in app--> gradle file. 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.0"
    defaultConfig {
        applicationId "com.example.androiddatabinding"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    dataBinding {
        enabled = true
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    
}

4. Create a book model : Book.java

package com.example.androiddatabinding;

public class Book {

    private String name;
    private String email;

    public Book(String name, String email) {
        this.name = name;
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

 

5. Create a layout for BookdetailActivity. 

Here layout structure is different.

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

    <data>
        <variable name="book" type="com.example.androiddatabinding.Book"/>
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        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=".BookDetailActivity"
       >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{book.name}"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{book.email}"
        android:textSize="20sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

6.  Now bind book model with layout.

package com.example.androiddatabinding;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.example.androiddatabinding.databinding.ActivityBookDetailBinding;

public class BookDetailActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_book_detail);
        ActivityBookDetailBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_book_detail);
        Book book = new Book("Book", "book@gmail.com");
        binding.setBook(book);
    }
}

Note :

1. Some time binding class is not generate so we have to do CLEAN or REBUILD.

2. Binding class name will be depends on your activity name.

Example :    BookDetailActivity -->> ActivityBookDetailBinding

 

Please download project code from here.  AndroidDataBinding 

---------------------------------------------

 Check out  my other useful blog :  A single adapter for multi view

Above is just a basic things to understand flow. Next week I’ll post top data binding with recycle view and adapter  that is very useful and mostly all apps using this. 

you can also suggest ideas for my next blog in comment section.

please click LIKE button and SHARE to help others to find it!

Thank you so much, Have a great day !


Click Here To See More

What's Your Reaction?

like
1
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0