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.
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.
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 } }
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" }
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!") } }
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 } }
There are many benefit to use the View Binding into android development.
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
Hi everyone, In this article, we are going to learn how to hide the production… Read More
Hello everyone, Today in this article, we are going to learn about localisation to support… Read More
Hello everyone, In this article, we are going to learn something to handle the callback… Read More
In this article, we are learning about the run time permissions for request permission launchers.… Read More
Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More
Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More