LoginSignup
28
21

More than 5 years have passed since last update.

KotlinでAndroid Databinding

Last updated at Posted at 2017-05-25

Data Binding

ModelとLayoutファイルのプロパティを紐付け、Modelのクラスを生成して渡すとViewに表示してくれるステキな機能でAndroidではライブラリで実現されています。
WindowsフォームなどのGUIプログラミングをやったことある人は知ってる概念かもしれません。

今回はしていませんが双方向バインディングするとViewへの入力をModelに反映も出来ます。

公式のドキュメントはもちろんJava向けなのでKotlinで実装してみます。

Gradle

// app gradle

apply plugin: 'kotlin-kapt'
...

android {
    ...
    dataBinding {
        enabled = true
    }
}

dependencies {
    ...
    kapt 'com.android.databinding:compiler:2.3.1'
}

kaptはData Bindingのためのものでは有りませんが、Data BindingのためのクラスがAnnotation Processingで生成されるので。KotlinでもAnnotation Processingに対応するためのプラグインを入れています。

バインディングするモデル作成

class User(var firstName: String, var lastName: String)

サンプルに習いfirstName,lastNameというプロパティを持つUserというモデルを作成します。

layout

// main_activity.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="user"
            type="com.example.myapplication.model.User" />
    </data>
<!-- もともとのRoot要素をLayoutでくるむ、xmlns:android="http://schemas.android.com/apk/res/android"が重複するので元々のroot要素からは削除 -->

・・・・・・
<!-- 追加 -->
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.firstName}"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{user.lastName}"/>
・・・・・・
</layout>
  • Root要素を「layout」にする
  • 「data」にModelの紐付けをする
  • Viewのandroid:text(など)に"@{user.firstName}"とプロパティを指定

Activity

// ActivityMain.kt
// onCreate
        val binding = DataBindingUtil.setContentView<MainActivityBinding>(this, R.layout.activity_main)
        val user = User("Test", "User")
        binding.user = user

DataBindingUtilを持ちいてバインドされたViewを取得。(←これの名称なんて言えばいいんですかね・・・・・・)
このViewのプロパティ(layoutファイルのdata->variable要素のname属性で定義したもの)にModelのクラスを渡すだけです。

28
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
21