DEV Community

Cover image for View Binding in Android.
Boris Ochieng
Boris Ochieng

Posted on • Updated on

View Binding in Android.

On the 23rd of November 2020, Google announced that Kotlin Synthetics had been deprecated where the findViewById() method was used to find an existing view in your XML layout by it's android:id attribute. Enter View Binding.

If you're like me, you often have to go back to the official documentation and read on how to integrate this into your project. I wrote this article as a quick reference for future me and probably youπŸ˜‰.

Enable view binding.

In your tool window bar, switch to Project View and under Gradle Scripts, in the app module, select the build.gradle file and set the viewBinding to true as shown below:

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}
Enter fullscreen mode Exit fullscreen mode

Behind the scenes, a binding class is generated for all the XML layout files. Each binding class holds references to the root view and all views that possess an ID. The name of the binding class comes from the name of the XML file. The name is changed to a special format called Pascal case and the word "Binding" is added to the end.
Suppose you have a layout file named activity_main.xml;

<RelativeLayout ...>
  <TextView android:id="@+id/hello" />
</RelativeLayout>
Enter fullscreen mode Exit fullscreen mode

The generated class will be named ActivityMainBinding with a TextView named hello.

Use view binding in activities.

In the MainActivity.kt file, add the following code or adjust accordingly:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}
Enter fullscreen mode Exit fullscreen mode

You can use the binding class to access any of the views now.

//change the text to "Hello World"
binding.hello.text = "Hello World"
//do something when clicked
binding.hello.setOnClickListener {
   //do something
}

Enter fullscreen mode Exit fullscreen mode

Use view binding in fragments.

Suppose you have a fragment named HelloWorld.kt with a layout file fragment_hello_world.xml. Add the following code or adjust accordingly:

private var _binding: FragmentHelloWorldBinding? = 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 = FragmentHelloWorldBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
Enter fullscreen mode Exit fullscreen mode

That's just about it, you can get an in depth look in the official documentation and a practical tutorial here.

Top comments (0)