安卓 Kotlin 使用 MVVM 基本步骤

步骤

1. 在plugins里添加id 'kotlin-kapt'

安卓 Kotlin 使用 MVVM 基本步骤_第1张图片

安卓 Kotlin 使用 MVVM 基本步骤_第2张图片

2. 在android里配置添加以下代码:

buildFeatures{
    dataBinding = true
}
kapt {
    generateStubs = true
}

安卓 Kotlin 使用 MVVM 基本步骤_第3张图片

安卓 Kotlin 使用 MVVM 基本步骤_第4张图片

3. 在dependencies里添加以下代码:

kapt  "com.android.databinding:compiler:4.1.3"

fc1c1b0ba5761eb3

这里有个4.1.3,是根据下面这个位置来的:

9426b1cce1e487ec

4. 此时的MainActivity,就不应该使用setContentView(R.layout.activity_main)了,而应该是:

class MainActivity: Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        val values = MainValues()
        binding.setVariable(BR.values, values)

        values.hello = "你好,世界"
    }
}

5. MainValues类是自定义的,其中存放着一些在界面显示的内容,例如字符串图片这样的,还可以包含点击事件的方法,此时里面只有一个hello变量。

6. activity_main.xml的内容:


<layout>
    <data>
        <variable
            name="values"
            type="xxx.xxx.xxx.MainValues" />
    data>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{values.hello}" />
    LinearLayout>
layout>

这样运行可以看到以下:

安卓 Kotlin 使用 MVVM 基本步骤_第5张图片

在应用onCreat()时更新的数据不用提示更新,但在其它地方,应该注意在更新数据需要显示时,调用binding.notifyPropertyChanged(BR.xx)或者binding.notifyChange()

没有标题栏经过以前尝试发现是因为这个Activity是继承的Activity()而不是AppCompatActivity(),至于细节就没探究了,与主题有关吧。

7. 至于点击事件

可以给按钮的onClick如此赋值:@{() -> values.onClick()}onClick是一个自定义的方法,可以传递参数,因此可以(view) -> values.onClick(view),以view作点击事件区分;也可以@{viewModel::click},不带参数。

结束

内容有错误欢迎指出,有遗漏很也欢迎补充,发这儿多是为了方便自己随时查看,当然完善点更是好事。

你可能感兴趣的:(安卓)