Member-only story

View Binding vs Data Binding Gotchas

Do I still need View Binding if I have already enabled Data Binding in my Android project?

Vincent Tsen
2 min readNov 13, 2021

Let’s say you have a fragment layout as below, and you want to add a View Binding into your project.

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />

</LinearLayout>

Enable View Binding

You enable this viewBinding in your build.gradle(module).

buildFeatures {  
viewBinding true
}

Then, you inflate the fragment layout in onCreateView()

override fun onCreateView(  
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {

val binding = FragmentFirstBinding.inflate(inflater)
// access view in this fragment
val textView = binding.textview
return binding.root
}

--

--

No responses yet