欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

如何使用databinding in kotlin

程序员文章站 2022-03-08 20:49:21
...

1.首先关键是配置好gradle:

in build.gradle(project): 

 ext.gradle_version = '3.0.1'

 in build.gradle(app)

apply plugin: 'kotlin-kapt'

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

dependencies{
...
kapt "com.android.databinding:compiler:$gradle_version"
}

//kapt "com.android.databinding:compiler:$gradle_version" 可以不用的 

 

2.layout:

<layout xmlns:android="http://schemas.android.com/apk/res/android">


    <data>
        <variable
            name="user"
            type="com.m.databindingdemo.model.User"/>
    </data>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <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}"
            />


    </LinearLayout>

</layout>

 

3.User:(注意,field不能private,要不会读取不了)

class User( val firstname: String,  val lastname: String)

 

4.activity:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        var user = User("Test", "User")
        binding.user = user
    }

 

相关标签: databinding kotlin