Skip to main content

DataBinding - ViewBinding in Android

ViewBinding is a feature that allow you to write code more easily.
 First we will see an App without ViewBinding then we will enable ViewBinding in the App .Screenshot of our app is , it is asimple application when we  click the Button score Will Increase


You can also see this tutorial in my youtube channel



you can download source code of this project from GitHub

Layout file is
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Score"
            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/tv_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="32dp"
            android:text="0"
            android:textSize="18sp"
            android:textStyle="bold"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/text1" />
        <Button
            android:id="@+id/bt_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="32dp"
            android:text="Play"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

 </androidx.constraintlayout.widget.ConstraintLayout>

 
Mainavtivity.kt

package com.arun.androidtutsforu.demonavgraphtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
class MainActivity : AppCompatActivity() {
    private var score =0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val tvScore = findviewById<TextView>(R.id.tv_score)
        val btPlay = findViewById<Button>(R.id.bt_play)
        btPlay.setOnClickListener {
            tvScore.text = (score++).toString()
        }

    }
}
 We use findViewById to reference views in our Activity , every time we use  findViewById android has to traverse the view hierarchy in runtime to find the view , when we use bigger apps with deep view hierarchy it can slow down our app

when we use DataBinding , It will connect our Activity to layout at compile time. The Compiler will create a binding class from our xml layout at compile time . Activity can now reference this binding class directly to access views . Name of the binding class will be same as the layout name with Binding at the end . Name of every view will be same as its id in the xml

To enable DataBinding first we need to enable it in our module level
build.gradle file

  buildFeatures{
    dataBinding true
  }
then convert our layout to DataBinding layout  . In dataBinding layouts, <layout> is the root element .You can convert your layout  easily to data binding layout in Android studio . Click on the root element press alt enter in keyboard , context menu will open ,in the context menu click convert to data binding layout. Your layout will be converted to data binding layout.
our new layout file is
activity_main.xml
<?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">
    <data>
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Score"
            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/tv_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="32dp"
            android:text="0"
            android:textSize="18sp"
            android:textStyle="bold"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/text1" />
        <Button
            android:id="@+id/bt_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="32dp"
            android:text="Play"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
You can see that our root element is changed to <layout> . Next build the app . The compiler will create a binding class for us. Name of the binding class will be ActivityMainBinding(because name of our xml layout file is activity_main). Now we can use the instance of this binding class to reference each view . Name of every view will be same as its id in the xml layout . Id of our button is bt_play and textview is tv_score.
Now we can reference both using our binding object
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btPlay
        binding.tvScore
      
we don't need to use findViewById anymore. ViewBinding help us to call the views quickly and easily. It also simplifies the code.
MainActivity.kt
package com.arun.androidtutsforu.demonavgraphtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.arun.androidtutsforu.demonavgraphtest.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
    private var score =0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btPlay.setOnClickListener {
            binding.tvScore.text = (score++).toString()
        }

    }
}
you download dource code from GitHub
https://github.com/arunkfedex/DemoNavGraphTest

Comments

Popular posts

Android List View using Custom Adapter and SQLite

following is a simple applicaton to create ListView using  Custom adapter.screenshot of the application  is like this . ListView is not used in android Anymore . We use  RecyclerView  and  CardView   in Android RecyclerView Demo is available on the following link http://androidtuts4u.blogspot.in/2017/04/android-recyclerview-example.html RecyclerView with Cardview Example is available on the following link http://androidtuts4u.blogspot.in/2017/09/android-card-view-example.html The ListView below the submit button is populated using Custom Adapter.Data is stored and retrieved using SQLite databsase. you can download the source code of this project from  google drive   https://drive.google.com/folderview?id=0BySLpWhqmbbdUXE5aTNhazludjQ&usp=sharing click on the above link ->sign into  your  google account ->add this to your google drive -> open it in google drive and download it. To create a simple ...

Android External database : Using database in "assets" folder

The best way to create a database application in android is , using an exteranal database . ie, we can create database  using tools like N avicat  , SQLite Browser  and copy this database into our application .This  method is more flexible and easy than creating a database in our application . This is a simple application using external database file.Application will insert data into database and show data from the database in a customized list view.  Screenshots of this application are MainActivity This is the first activity of this application . When  Register Here button is pressed it will start Registration Activity Editing of the entries can be done with a Long Click on the listView items. you can download the source code of this project from  google drive  https://drive.google.com/folderview?id=0BySLpWhqmbbdY3JHMkZRZFN0bEE&usp=sharing click on the above link ->sign into  your  google account ->a...

Keytool is not recognized as internal or extenal command / Adding PATH in system variable

If you are running a keytool command  keytool -list -v -keystore C:\Users\arun\.android\debug.keystore -alias androiddebugkey -storepass android    and getting an error   'keytool' is not recognized as an internal or external command  If you are using any other commad like java,javac , etc.. and getting an error " is not recognized as an internal or external command"  you can also use this same steps  you are getting this error because keytool.exe , executable file which exists in the bin directory of your JDK  is not added to Path in your Environmental variables. To resolve this issue 1 .first we need to find the bin Directory of our jdk    Usually this will be in  C:\Program Files\Java\jre1.8.0_221\bin (jre1.8.0_221 - change this to your latest version , ). you can see keytool.exe file in the bin directory . (If you installed jdk in a different directory Find your Jdk installation folder and  use that path....