Databindingutil setcontentview android kotlin

Урок 8. Android Data Binding – основы

Продолжаем курс по обучению основам разработки мобильных приложений в Android Studio на языке Kotlin. В этом уроке познакомимся с Android Data Binding.

Data Binding Library

Библиотека Data Binding Library, которая является частью Android Jetpack, позволяет привязывать компоненты пользовательского интерфейса в макетах к источникам данных в приложении, используя декларативный формат, а не программно. Другими словами, Data Binding поможет организовать работу с View так, чтобы нам не пришлось писать кучу методов findViewById, setText, setOnClickListener и т.п.

Чтобы более тесно на практике познакомиться с чистой архитектурой и архитектурными компонентами, записывайтесь на продвинутый курс по разработке приложения «Чат-мессенжер»

В этом цикле уроков вы узнаете, как настроить Data Binding в проекте, что такое layout expressions, как работать с observable objects и как создавать кастомные Binding Adapters чтобы свести избыточность (boilerplate) вашего кода к минимуму.

С чего начать

В этом уроке, мы возьмем уже существующий проект и конвертируем его в Data Binding:

Приложение имеет один экран, который показывает некоторые статические данные и некоторые наблюдаемые данные, что означает, что при изменении данных пользовательский интерфейс будет автоматически обновляться. Данные предоставлены ViewModel. Model-View-ViewModel — это шаблон уровня представления, который очень хорошо работает с Data Binding. Вот диаграмма паттерна MVVM:

Если вы еще не знакомы с классом ViewModel из библиотек компонентов архитектуры, вы можете посмотреть официальную документацию. Мы знакомились с этим классом на прошлом уроке, ссылку на который вы видите в правом верхнем углу этого видео. Это класс, который предоставляет состояние пользовательского интерфейса для представления (Activity, Fragment, т.п.). Он выдерживает изменения ориентации и действует как интерфейс для остальных слоев вашего приложения.

Что нам понадобится

  • Среда разработки Android Studio 3.4 или более новой версии.
  • Приложение без Data Binding

На этом этапе мы загрузим и запустим простое приложение-пример. Выполните в консоли команду:

Вы также можете клонировать или скачать репозиторий в виде Zip-файла по ссылке на GitHub

  1. Распакуйте проект
  2. Откройте проект в Android Studio версии 3.4 или выше.
  3. Запустите приложение

Экран по умолчанию открывается и выглядит так:

Этот экран отображает несколько различных полей и кнопку, по нажатию которой можно увеличить счетчик, обновить индикатор выполнения и изображение. Логика действий, происходящих на экране, описана в классе SimpleViewModel. Откройте его и посмотрите.

Используйте Ctrl + N, чтобы быстро найти класс в Android Studio. Используйте Ctrl + Shift + N, чтобы найти файл по его имени.

На Mac найдите класс с помощью Command + O и файл с помощью Command + Shift + O.

В классе SimpleViewModel описаны такие поля:

  • Имя и фамилия
  • Количество лайков
  • Уровень популярности

Кроме того, он позволяет пользователю увеличивать количество лайков методом onLike().

Пока SimpleViewModel содержит не самый интересный функционал, но здесь все в порядке. С другой стороны, класс главного экрана MainActivity имеет ряд проблем:

  • Он вызывает метод findViewById несколько раз. Это не только медленно, но и небезопасно, потому что не проверяется на ошибки времени компиляции. Если идентификатор, который вы передаете в findViewById, неправильный, приложение аварийно завершит работу во время выполнения.
  • Устанавливает начальные значения в onCreate. Было бы намного лучше иметь значения по умолчанию, которые устанавливаются автоматически.
  • Использует в макете атрибут android:onClick который также не является безопасным: если метод onLike не реализован в активити (или переименован), приложение упадет в рантайме.
  • В нем много кода. Активити и фрагменты имеют тенденцию расти очень быстро, поэтому желателно удалить из них как можно больше кода. Кроме того, код в активити и фрагментах трудно тестировать и поддерживать.

В нашей серии уроков с помощью библиотеки Data Binding мы собираемся исправить все эти проблемы, переместив логику из активити в места, где ее можно повторно использовать и проще тестировать.

Подключаем Data Binding в проект

Первым шагом является включение библиотеки Data Binding в модули, которые будут ее использовать. Добавьте такие строки в файл сборки модуля app:

Источник

Android databinding, with Kotlin!

The MVVM design pattern allows us to write code that is much easier to maintain, test, and reason about in Android development. In this post, we will describe how to setup an application for databinding using the `MVVM` pattern in Kotlin, although many of the concepts are also equally valid for `MVP`

Читайте также:  Виртуал андроид рут права

Getting Started

This post walks through the steps to set up Android databinding using the MVVM pattern in Kotlin. If you learn best by playing directly with code, I have provided a simple sample app that that implements all of the features discussed below.

First Steps

First we require a few prerequisites for our Android project:

Add the Kotlin plugin to your gradle file:

Enable databinding in the gradle file:

Add databinding as a kapt dependency

Add the Kotlin standard library as a dependency

What is Android data binding, and why should I use it?

Android data binding allows for 1 or 2-way binding within the layout XML files of Android. This should be familiar to anyone who has done web based development with Angular or Ember, or C# WPF development.

The most basic case is to add an on-click listener. This requires no registering of on click listeners in any of your application code, just some XML in the layout file and a function to be called in your ViewModel class

If you are new to databinding the above might look a bit odd — why is my root element , what is this tag, what is that crazy string in the onClick attribute? Do not worry if it is confusing now, we will walk you through it line by line.

First the layout element:

All Android layout files that you wish to enable databinding for must start with this tag. This tag will only contain namespace declarations, not any height or width specifications. It will then include any layout or view within it as a child element, just as you would any other layout file.

This namespace gives access to the app attributes. These are custom attributes provided by either your project (more on this later!), or by the Android library itself. An example will be shown later of this in action.

The data tag is used to include all your Java / Kotlin values you wish to inject into the layout file.

The import tag is used to import any type that is used within the layout. Later we will show you an example utilising this concept to determine the visibility of the view.

The variable tag is used to store any values that will be used in the layout. In this case the DemoViewModel class is loaded as it contains the business logic which will control this view.

Here we are accessing the boolean field on the DemoViewModel called buttonVisible , and if it is true, then we are setting the visibility of the Button to View.VISIBLE , otherwise we are setting it to View.GONE . These values from the View class require an import as described above.

Here we can register a lambda which, when the user clicks on the button, will execute the provided code. In our case it will just call the buttonClicked method on the DemoViewModel class.

Finally we are binding the standard android attribute android:text to the string value contained in the field text in the DemoViewModel class. The syntax looks a bit weird but basically @ is used to tell the auto generated data binding class to replace this value, with whatever is inside the vm.text field. For 2 way binding (e.g. changes on a text view update the value in the view model) then the sytax would be @= , e.g. @= .

Setting up a view for Databinding

In order to actually use databinding we need to set the content view of our activity using the Android provided android.databinding.DataBindingUtil class. This will return an auto generated ViewDataBinding class specific to our layout XML file, which allows us to inject any variables we need. In this case we need to inject the DemoViewModel class into the layout.

As you can see with the above code there is no need to directly access any View elements in the code, and all business logic is handled within the ViewModel , with the minimum just to setup the view inside the Activity .

Читайте также:  Сетевой пульт ду samsung android

The only odd thing in the above code is the use of ObservableField . An ObservableField is a simple data wrapper which will allow the layout to be notified whenever the value has changed. After using the set method in the buttonClicked function, it will update the internal String with the new value, and then notify any listeners (in our case the layout) of the change. The ObservableField can be used for any type as it allows generics e.g. ObservableField , ObservableField .

Creating your own custom attributes

So the MVVM architecture looks great right? What about if we want to change the text color of the TextView dynamically based on character length? Does that mean we have to reference the View within our ViewModel (breaking the idea that no Android specific code should be in the ViewModel )? We don’t have to! There are two ways to create your own custom attributes for a view.

First we will create some helpful extension methods to make detecting text changes easier:

Then, using a @BindingAdapter(«myCustomAttribute») annotation you can specify package function as a handler for a view’s attribute:

Or an alternative way is to create a custom view which will contain your business logic:

Then in the layout, regardless of which of the above approaches are used, you bind some data to your new attribute:

How does databinding work?

In order for the layout to interact with these injected values some glue code is generated by Android. This glue code will handle the on click listeners, binding adapters, and 2 way binding for us. So as developers we can just focus on the actual business logic.

Sample app

You can find the sample app that implements all of the features discussed above here: https://github.com/instil/kotlin-databinding

Wrapping up

Here at Instil we have been very much swept off our feet by the power and readability offered by Kotlin. The best bit being you don’t have to stop using any of the best practices you already know from Java, as Kotlin has such strong interoperability with Java while also being backed up by the fantastic tooling provided by Jetbrains in both IntelliJ and Android Studio.

Источник

Android’s Data Binding with Kotlin

Apr 8, 2017 · 3 min read

I assume you are (or you are trying to be) an Android developer. Then I ask: have you already tried to use Data Binding?

It’s a library which allows you to bind the data of your models directly to the xml views in a very flexible way.

My first experience with this was a year ago, trying t o set more than 10 different fonts to the Android App I was developing at that moment. For me that was the discovery of a powerful tool. By then, another powerful tool I was flirting with during that period of time was the programming language called Kotlin.

Now in this post I want to show you the approach I used to mix the power of Data Binding with Kotlin with a simple example.

First of all, after having a created Android project in Android Studio, we need to add the Data Binding dependency and the ones of Kotlin to the build.gradle file of our app.

That’s all the configuration we need to start using Data Binding with Kotlin. Thank you very much for reading me… Now lets continue with the fun starting to see the code.

First we need to create a model. In this case a basic one like User.kt

In our activity_main.xml we can do something like this:

Remember to always set your usual xml view inside the tag and attach all the “xmlns:” properties to it. Otherwise it will throw a compilation error, since the generated files will have duplicated properties.

And here comes the Binding:

In that code snippet there are somethings to be noticed:
*Now exists a class called ActivityMainBinding, which is autogenerated from the activity_main.xml and this contains all the references to use the views that the xml contains.
*The way of making an instance of ActivityMainBinding is a little variation of the way of setting the xml layout to an activity.
*There is also a new BR class which is some kind of secondary R class used to store the variables declared on the data tag of the xml.
*After setting the variable to the binding object, it is necessary to call the executePendingBindings() in order to set the user variable attributes to the marked views.

Читайте также:  Store and share android

After compiling this you’ll be able to see that the Data has been set to your view without the necessity of writing any textView.text = user.name

This was my simple approach to use DataBinding inside a Kotlin project. I hope this is being useful to you.

Источник

Урок 18. Android Data Binding. Основы

В этом уроке знакомимся с Data Binding.

Полный список уроков курса:

В build.gradle файл модуля в секции android необходимо включить Data Binding:

Правильно произносить байндинг , но биндинг звучит проще — буду использовать его.

Data Binding поможет организовать работу с View так, чтобы нам не пришлось писать кучу методов findViewById, setText, setOnClickListener и т.п. Давайте рассмотрим простой пример.

Есть класс Employee, который содержит в себе данные о работнике

поля: id, имя и адрес.

Мы хотим вывести имя и адрес работника на экран main_activity.xml:

Несложная задача. Для этого мы обычно пишем методы findViewById и setText. Тут все понятно.

Давайте рассмотрим, как это же можно сделать с помощью Data Binding.

Вносим изменения в main_activity.xml:

Корневым элементом теперь является , а LinearLayout сместился внутрь него.

В секции data мы объявляем переменную с именем employee. Ее тип — ранее рассмотренный класс Employee. Теперь мы можем использовать эту переменную в атрибутах вьюшек этого layout. В первом TextView, в атрибуте text мы используем employee.name, а в втором TextView — employee.address.

Обратите внимание, что мы не указываем id для View. В этом нет необходимости.

Как вы понимаете, нам остается лишь передать объект Employee в этот layout. И значения этого объекта будут подставлены в соответствующие TextView.

Это делается следующим образом.

Сначала создаем Employee объект.

Затем используем DataBindingUtil. Метод DataBindingUtil.setContentView внутри себя сделает привычный нам setContentView для Activity, а также настроит и вернет объект биндинга MainActivityBinding.

MainActivityBinding — это сгенерированный класс. Имя этого класса берется из имени layout файла (т.е. main_activity), плюс слово Binding. MainActivityBinding все знает о нашем layout: какие View там есть, какие переменные (variable) мы там указывали, и как все это связать друг с другом, чтобы данные из переменных попадали в View.

Метод setEmployee был сгенерирован в классе биндинга, т.к. мы описали переменную employee в layout файле. Этим методом мы передаем биндингу объект Employee. Биндинг возьмет значения employee.name и employee.address и поместит их (методом setText) в соответствующие TextView. Все, как мы и настраивали в layout.

Данные из Employee помещены в TextView.

Сразу хочу заметить, что если мы теперь в коде будем изменять объект Employee, то данные на экране меняться не будут. Они считались один раз и далее не отслеживаются (при такой реализации).

Чтобы экран получил новые данные, надо снова передать биндингу измененный объект Employee:

Или можно вызывать метод invalidateAll:

Биндинг считает новые данные с ранее полученного объекта Employee.

Поля в Employee в этом примере я сделал public. Но вы можете сделать их private и создать для них public get методы.

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

Кроме того, мы рассмотрели совсем простой случай использования биндинга. Но его возможности гораздо шире. Например, можно сделать так, чтобы при передаче в атрибут ImageView ссылки на картинку, биндинг запускал Picasso для загрузки этой картинки и помещал результат в ImageView. Или биндинг может сам отслеживать изменения в объекте с данными (в примере выше — это Employee ) и обновлять экран без каких-либо дополнительных методов.

Эти возможности мы рассмотрим в следующих уроках.

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

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