Why View Binding need to use in android?
As for making screen in android app development, we need to write a xml inside the res layout folder of our project structure which needs to inflate with view either Activity or Fragments. We have used so many view components into our xml which need to get the id of each component in our view to use to inflate the real data. So for we used the findViewById keyword to get the Id of the view component from the xml layout in the View Class. In this case we have to write the boilerplate code in our view for multiple view components.
To avoid this we need to use the concept of view binding feature to get the all artefacts of view easily. Let’s see how to use the view binding and what are the major benefit to use this feature.
What is View Binding?
View Binding is a feature that brings better interactions with views. It generates the Binding class for each XML layout, which contains all the references to the views with an ID. The name of this generated class is the XML name in Pascal Case and the word Binding at the end.
For example, activity_main.xml becomes ActivityMainBinding.
How to add View Binding?
ViewBinding is the code feature of android architecture component. So for we do not need to add any dependency into our gradle. we just need to enable the flag to use this feature which is already part of the Gradle plugin and you need to use the latest Android Studio 3.6 and higher.
android { ... buildFeatures { viewBinding = true } }
How to use View Binding in the Activity Class?
Suppose, we have MainActivity Class as an Activity and corresponding we use the xml layout name activity_main. Then Gradle plugin will auto generate the corresponding Binding class at compile time only. Lets see an example..
private lateinit var ui: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ui = ActivityMainBinding.inflate(layoutInflater).apply { setContentView(root) } ui.title.text = "View Binding" }
How to use View Binding in the Fragment Class?
Suppose, we are using the xml layout name fragment_main.xml and Gradle plugin will auto generate the binding class name at the end of file name. As fragment is more tight attached with lifecycle of Activity class, which need to give more attention while fragment view destroy to make the reference null to avoid the memory leak. Let’s see an example.
private var binding: FragmentMainBinding? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentMainBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() binding = null }
Even, we can make something better to write in one line by using the extension function of View Binding. We need to add few dependencies into our gradle file.
implementation "androidx.lifecycle:lifecycle-runtime:2.2.0" implementation "androidx.lifecycle:lifecycle-common-java8:2.2.0" implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0" implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
You can this extension code in side any util package.
fun <T : ViewBinding> Fragment.viewBinding(viewBindingFactory: (View) -> T) = FragmentViewBindingDelegate(this, viewBindingFactory) class FragmentViewBindingDelegate<T : ViewBinding>( val fragment: Fragment, val viewBindingFactory: (View) -> T ) : ReadOnlyProperty<Fragment, T> { private var binding: T? = null init { fragment.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onCreate(owner: LifecycleOwner) { fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner -> viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { binding = null } }) } } }) } override fun getValue(thisRef: Fragment, property: KProperty<*>): T { val binding = binding if (binding != null) { return binding } val lifecycle = fragment.viewLifecycleOwner.lifecycle if (!lifecycle.currentState.isAtLeast(Lifecycle.State.INITIALIZED)) { throw IllegalStateException("Should not attempt to get bindings when Fragment views are destroyed.") } return viewBindingFactory(thisRef.requireView()).also { this.binding = it } } }
Then it will take care while life cycle change, you do not worry about it.
In Activity Class
class MainActivity : AppCompatActivity() { private val binding by viewBinding(MainActivityBinding::inflate) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) binding.button.onClick { showToast("hello world!") }
In Fragment Class
class MainFragment: Fragment(R.layout.first_fragment) { private val binding by viewBinding(MainFragmentBinding::bind) override fun onViewCreated(view: View, bundle: Bundle?) { super.onViewCreated(view, bundle) binding.buttonPressMe.onClick { showToast("Hello binding!") } }
How to use View Binding in adapters?
View Binding is not only limited to use only Activity and Fragment, you can free to use any places for example in adapter class as well. we can pass the View Binding directly to the view holders. Let’s see an example.
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = HeaderViewHolder( ItemHeaderBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) class HeaderViewHolder(val binding: ItemHeaderBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: HeaderData) { binding.name.text = item.name } }
Benefit to use View Binding?
There are many benefit to use the View Binding into android development.
- If we use this feature then definitely our development will be very fast. Developer do not much focus on find the id of view to use to inflate the data. they can be give more attentions on their business logic.
- Most time we face null pointer exceptions because of developer mistake, to avoid this we can use this feature to make every things will be null safe.
- Gradle plugin takes cares autogenerate the corresponding the Binding class at compile time to make easy to use.
Conclusion:
As we saw here, View Binding is a better way to handle work with the views both in terms of safety and speed. It’s also simple to use, the library does almost everything for you
If you are wondering to learn Android then Please learn from Android category and wondering to learn Kotlin then Kotlin Category will help you. If you want to learn all the python article, then learn from the python category.
Happy Coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com