Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

View Binding in Android Jetpack

View Binding is a feature in Android Jetpack that allows you to more easily write code that interacts with views. It generates a binding class for each XML layout file present in that module. By using view binding, you ensure that the views that you interact with are non-null, which can help eliminate the risk of null pointer exceptions, and it's type-safe. Here's how you can use it:

1. Set Up View Binding:

In your module's build.gradle file:

android {
    ...
    viewBinding {
        enabled = true
    }
}

After you've set it up, you need to rebuild your project.

2. Use View Binding in Activities:

Assuming you have an XML layout named activity_main.xml, View Binding will generate a binding class named ActivityMainBinding.

Here's how to use it in an Activity:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.myapp.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Use binding to access views
        binding.textView.text = "Hello, View Binding!"
    }
}

3. Use View Binding in Fragments:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.example.myapp.databinding.FragmentExampleBinding

class ExampleFragment : Fragment() {

    private var _binding: FragmentExampleBinding? = null
    // This property is only valid between onCreateView and onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentExampleBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.textView.text = "Hello from Fragment!"
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

Note: In fragments, it's recommended to clean up the binding reference in onDestroyView() to avoid memory leaks.

Benefits of View Binding:

  • Null safety: By using View Binding, all the views that have an ID in the XML layout will be available in the binding class as non-null properties. This means you won't face a NullPointerException from trying to access views.

  • Type safety: Each view in the binding class is strongly typed, so there's no risk of a class cast exception.

  • Performance: View Binding does not rely on reflection, as is the case with some other libraries. This means there's a slight performance edge by using View Binding.

However, remember that View Binding is not a replacement for data binding. They serve different purposes. Data Binding library allows you to bind UI components in your layouts directly to data sources and can reduce boilerplate code. View Binding simply provides a way to more easily access views.

  1. Enabling View Binding in Android Jetpack project:

    • Description: Enables View Binding in your Android project, allowing for a type-safe and efficient way to interact with views.
    • Code: Add the following to your app-level build.gradle file:
      android {
          ...
          viewBinding {
              enabled = true
          }
      }
      
  2. Using View Binding with Fragments in Android:

    • Description: Utilizes View Binding within Fragments for streamlined view access.
    • Code:
      // In your Fragment
      private var binding: FragmentExampleBinding? = null
      
      override fun onCreateView(
          inflater: LayoutInflater, container: ViewGroup?,
          savedInstanceState: Bundle?
      ): View {
          binding = FragmentExampleBinding.inflate(inflater, container, false)
          return binding!!.root
      }
      
  3. View Binding vs findViewById in Android:

    • Description: Compares the traditional findViewById approach with the benefits of View Binding.
    • Code:
      // findViewById
      TextView textView = findViewById(R.id.textView);
      
      // View Binding
      TextView textView = binding.textView;
      
  4. Incorporating View Binding with RecyclerView in Android:

    • Description: Enhances RecyclerView integration using View Binding for efficient and type-safe view access.
    • Code:
      class MyAdapter(private val items: List<String>) :
          RecyclerView.Adapter<MyAdapter.ViewHolder>() {
      
          inner class ViewHolder(private val binding: ItemExampleBinding) :
              RecyclerView.ViewHolder(binding.root) {
              fun bind(item: String) {
                  binding.textView.text = item
              }
          }
      
          override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
              val binding = ItemExampleBinding.inflate(LayoutInflater.from(parent.context), parent, false)
              return ViewHolder(binding)
          }
      
          override fun onBindViewHolder(holder: ViewHolder, position: Int) {
              holder.bind(items[position])
          }
      
          override fun getItemCount(): Int {
              return items.size
          }
      }
      
  5. View Binding and Kotlin Android Extensions comparison:

    • Description: Compares View Binding with Kotlin Android Extensions for view access in Kotlin.
    • Code:
      // Kotlin Android Extensions
      textView.text = "Hello, Kotlin Android Extensions!"
      
      // View Binding
      binding.textView.text = "Hello, View Binding!"
      
  6. Working with included layouts and View Binding in Android:

    • Description: Explains how to use View Binding with included layouts for modular design.
    • Code:
      <!-- parent_layout.xml -->
      <include layout="@layout/included_layout" />