Android studio viewbinding что это

View Binding in Android

We have learnt that every time we need to access a view from our XML layout into our Java or Kotlin code, we must use findViewById(). It was okay for small/personal projects where we use 5 to 6 views in a layout. But for larger projects we have comparatively more views in a layout, and accessing each view using the same findViewById() is not really comfortable.

What is View Binding?

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module

Simply put, this allows us to access the views from the layout file in a very simple way by linking variables of our Kotlin or Java code with the XML views. When a layout is inflated, it creates a Binding object, which contains all the XML views that are casted to the correct type. This makes it really easier for us since we can retrieve all views in one line of code.

Getting started with View Binding

  1. Let’s start by enabling view binding in our project:

In build.gradle(:app) add the code in -> android

2. Before the onCreate() method, we create our binding object

3. Perform the following steps in onCreate() method:

  • Call the inflate() method to create an instance of the binding class for the activity to use.
  • Get reference to the root view
  • Pass the root view to setContentView() [setContentView(binding.root)] instead of layout [setContentView(R.id.activity_main)]

4. To get reference of any view, we can use the binding object:

Using View Binding in Fragments

We follow the same steps:

  1. Before the onCreateView() method, we create our binding object

2. Initialize our binding object in onCreateView()

3. To get reference of any view, we can use the binding object

Note: The name of the binding class is generated by converting the name of the XML file to camel case and adding the word “Binding” to the end. Similarly, the reference for each view is generated by removing underscores and converting the view name to camel case . For example, activity_main.xml becomes ActivityMainBinding, and you can access @id/text_view as binding.textView.

View binding has important advantages over using findViewById():

  • Null safety: Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID.
  • Type safety: The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception.

Start using View Binding

If you’re intrigued by View Binding and want to learn more about it, here’s some resources for you to learn:

One-Liner ViewBinding Library

You would have noticed that to use View Binding, we need to call the static inflate() method included in the generated binding class ( which creates an instance of the binding class for the activity or fragment )

Читайте также:  Как обновить скачанную прошивку андроид

Yesterday I came across an awesome library that makes ViewBinding one-liner ( By removing the boilerplate code and easily set ViewBindings with a single line )

One-liner ViewBinding Library : [Click Here]

Источник

Долгожданный View Binding в Android

Пару дней назад Google выпустил Android Studio 3.6 Canary 11, главным нововведением в которой стал View Binding, о котором было рассказано еще в мае на Google I/O 2019.

View Binding — это инструмент, который позволяет проще писать код для взаимодейтсвия с view. При включении View Binding в определенном модуле он генерирует binding классы для каждого файла разметки (layout) в модуле. Объект сгенерированного binding класса содержит ссылки на все view из файла разметки, для которых указан android:id .

Как включить

Чтобы включить View Binding в модуле надо добавить элемент в файл build.gradle :

Также можно указать, что для определенного файла разметки генерировать binding класс не надо. Для этого надо указать аттрибут tools:viewBindingIgnore=»true» в корневой view в нужном файле разметки.

Как использовать

Каждый сгенерированный binding класс содержит ссылку на корневой view разметки ( root ) и ссылки на все view, которые имеют id. Имя генерируемого класса формируется как «название файла разметки», переведенное в camel case + «Binding».

Например, для файла разметки result_profile.xml :

Будет сгенерирован класс ResultProfileBinding , содержащий 2 поля: TextView name и Button button . Для ImageView ничего сгенерировано не будет, как как оно не имеет id . Также в классе ResultProfileBinding будет метод getRoot() , возвращающий корневой LinearLayout .

Чтобы создать объект класса ResultProfileBinding , надо вызвать статический метод inflate() . После этого можно использовать корневой view как content view в Activity :

Позже binding можно использовать для получения view:

Отличия от других подходов

Главные преимущества View Binding — это Null safety и Type safety.

При этом, если какая-то view имеется в одной конфигурации разметки, но отсутствует в другой ( layout-land , например), то для нее в binding классе будет сгенерировано @Nullable поле.

Также, если в разных конфигурациях разметки имеются view с одинаковыми id, но разными типами, то для них будет сгенерировано поле с типом android.view.View .
(По крайней мере, в версии 3.6 Canary 11)

А вообще, было бы удобно, если бы сгенерированное поле имело наиболее возможный специфичный тип. Например, чтобы для Button в одной конфигурации и TextView в другой генерировалось поле с типом TextView ( public class Button extends TextView ).

При использовании View Binding все несоответствия между разметкой и кодом будут выявляться на этапе компиляции, что позволит избежать ненужных ошибок во время работы приложения.

Использование в RecyclerView.ViewHolder

Ничего не мешает использовать View Binding при создании view для RecyclerView.ViewHolder :

Однако, для создания такого ViewHolder придется написать немного бойлерплейта:

Было бы удобнее, если при работе с RecyclerView.ViewHolder метод inflate(. ) не будет иметь параметр layoutInflater , а будет сам получать его из передаваемого parent .

Тут нужно ещё упомянуть, что при использовании View Binding поиск view через findViewById() производится только один раз при вызове метода inflate() . Это дает преимущество над kotlin-android-extensions , в котором кеширование view по умолчанию работало только в Activity и Fragment , а для RecyclerView.ViewHolder требовалась дополнительная настройка.

В целом, View Binding это очень удобная вещь, которую легко начать использовать в существующих проектах. Создатель Butter Knife уже рекомендует переключаться на View Binding.

Немного жаль, что такой инструмент не появился несколько лет назад.

Источник

How to use View Binding in Android using Kotlin

In Android Studio 4.1+, when you create a new Kotlin project and try to connect an XML layout file with your .kt file using Kotlinx synthetic, you’ll see you can’t do it anymore.

This is because they removed the plugin ‘Kotlin Android Extensions‘ as JetBrains deprecated it in the 1.4.20 version of Kotlin.

Now, the alternatives are:

  • ButterKnife
  • findViewById()
  • View Binding

In this tutorial, I’ll show you how to implement View Binding in:

Читайте также:  Real driving school много денег для андроид

Enabling View Binding

In your module-level build.gradle file, add the following code to enable view binding.

This automatically will create binding classes for each XML file present in that module.

For example, if an XML file name is activity_main.xml, the generated binding class will have the name of this file in Pascal case and the word ‘Binding‘ at the end.

So the binding class will be ActivityMainBinding

If you don’t want to generate a binding class for a specific XML file, add the attribute tools:viewBindingIgnore=»true» in the root layout like that:

Using View Binding in Activities

To use View Binding in Activity, create an instance of the binding class, get the root view, and pass it to setContentView().

Now, you can reference your views like that:

Using View Binding in Fragments

There are two methods to use View Binding in Fragments:

Inflate: You do the layout inflation and the binding inside the onCreateView method.

Bind: You use an alternative Fragment() constructor that inflates the layout, and you do the binding inside the onViewCreated method

• Inflate method

In the onCreateView method, inflate your layout file and create the binding instance:

Because Fragments continue to live after the View has gone, it’s good to remove any references to the binding class instance:

• Bind method

At the top of your file, in the Fragment() constructor add your XML layout file, and create the binding inside the onViewCreated method (NOT the onCreateView):

Like I said before in the Inflate method, remove any references in the fragment’s onDestroyView() method:

Using View Binding in RecyclerView Adapter

To use View Binding in your RecyclerView adapter, add the binding class in your ItemViewHolder, and set the root layout:

Next, in the onCreateViewHolder method, do the layout inflation and return the ItemViewHolder with the binding.

And at the end, on the onBindViewHolder, you can reference any of the views through the binding of the holder:

If you have any questions, please feel free to leave a comment below

Источник

Android ViewBinding Tutorial

In this lesson we will look at ViewBinding, it’s advantages, how to set it up and how to use it.

What is ViewBinding?

According to android’s documentation:

View binding is a feature that allows you to more easily write code that interacts with views.

You can think of viewBinding as a replacement for findViewById function.

You enable it first in the build.gradle file and after that it will generate binding classes for your XML layouts. The instance of those generated classes will contain direct references to all views that have IDs.

How to setup ViewBinding

Step 1: Enable ViewBinding in Gradle

Go to your app level build.gradle file add the following inside the android closure:

Step 2: Your Layouts

There is nothing you need to add to your layouts for them to be eligible for ViewBinding. However if you want a layout to be ignore, then add the tools:viewBindingIgnore=»true» as follows:

Step 3: Code

In your activity declare the following:

Take note that our layout file is activity_main.xml .

Then in your onCreate method inflate the ActivityMainBinding:

Now obtain the root and set it as the contentView:

Now you can reference views, for example to reference a recyclerview with id ` rvMain :

Advantages of ViewBinding

  • Null safety — Same as data binding
  • Type safety — Same as data binding
  • No boilerplate code — Unlike in data binding, all layouts are by default eligible for the generation of binding class without any tag.
  • No impact on build time — Unlike in data binding, there is no negative impact on the build time.
  • Supports both Kotlin and Java.
Читайте также:  Как сменить шрифт системы андроид

Top ViewBinding Questions

ViewBinding vs Kotlin Android Extensions with synthetic views

Configuration

Kotlin Android Extensions

  1. Import appropriate layout synthetic extensions: import kotlinx.android.synthetic.main. .*
  2. Reference views in code via their ids: textView.text = «Hello, world!» . These extensions work on: Activities , Fragments and Views .

View Binding

  1. Create binding reference inside your class: private lateinit var binding YourClassBinding
  2. Inflate your binding binding = YourClassBinding.inflate(layoutInflater) inside Activity ‘s onCreate and call setContentView(binding.root) , or inflate it in Fragment ‘s onCreateView then return it: return binding.root
  3. Reference views in code via binding using their ids binding.textView.text = «Hello, world!»

Type safety

Kotlin Android Extensions and ViewBinding are type safe by definition, because referenced views are already casted to appropriate types.

Null safety

Kotlin Android Extensions and ViewBinding are both null safe. ViewBinding doesn’t have any advantage here. In case of KAE, if view is present only in some layout configurations, IDE will point that out for you:

So you just treat it as any other nullable type in Kotlin, and the error will disappear:

Applying layout changes

In case of Kotlin Android Extensions, layout changes instantly translate to generation of synthetic extensions, so you can use them right away. In case of ViewBinding, you have to build your project

Incorrect layout usage

In case of Kotlin Android Extensions, it is possible to import incorrect layout synthetic extensions, thus causing NullPointerException . The same applies to ViewBinding, since we can import wrong Binding class. Although, it is more probable to overlook incorrect import than incorrect class name, especially if layout file is well named after Activity / Fragment / View , so ViewBinding has upper hand here.

Data Binding vs ViewBinding

ViewBinding

Only binding views to code.

DataBinding

Binding data (from code) to views + ViewBinding (Binding views to code)

There are three important differences

With view binding, the layouts do not need a layout tag

You can’t use viewbinding to bind layouts with data in xml (No binding expressions, no BindingAdapters nor two-way binding with viewbinding)

The main advantages of viewbinding are speed and efficiency. It has a shorter build time because it avoids the overhead and performance issues associated with databinding due to annotation processors affecting databinding’s build time.

In short, there is nothing viewbinding can do that databinding cannot do (though at cost of longer build times) and there are a lot databinding can do that viewbinding can»t

Also:

Differences Between View Binding and Data Binding

View Binding library is faster than Data Binding library as it is not utilising annotation processors underneath, and when it comes to compile time speed View Binding is more efficient.

The one and only function of View Binding is to bind the views in the code. While Data Binding offers some more options like Binding Expressions, which allows us to write expressions the connect variables to the views in the layout.

Data Binding library works with Observable Data objects, you don’t have to worry about refreshing the UI when underlying data changes.

Data Binding library provides us with Binding Adapters.

Data Binding library provides us with Two way Data Binding, this is a technique of binding your objects to xml layouts, so that both object and layout can send data to each other.

Reference

report this ad

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Оцените статью